【问题标题】:How to Include 2 Models in 1 Form?如何在 1 个表单中包含 2 个模型?
【发布时间】:2015-03-09 11:29:27
【问题描述】:

一个模型创建 :name, :metric (Quantified.rb),另一个创建 :result_value, :result_date (Result.rb)。

class Quantified < ActiveRecord::Base
	belongs_to :user
 	scope :averaged,  -> { where(categories: 'Monthly Average') }
 	scope :instance,  -> { where(categories: 'One-Time Instance') }
 	has_many :results

	CATEGORIES = ['Monthly Average', 'One-Time Instance']

end


class Result < ActiveRecord::Base
		belongs_to :user
		belongs_to :quantified
end

我需要在 _form 和/或控制器中做什么才能允许用户将他的 results_date 和 results_value(results_form)添加到相应的名称和指标(quantifieds_form)?

<%= form_for(@quantified) do |f| %>
  <% if @quantified.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@quantified.errors.count, "error") %> prohibited this quantified from being saved:</h2>

      <ul>
      <% @quantified.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<div class="america">
<form>
   <%= f.select :categories, Quantified::CATEGORIES %>

   <br>
   <br>

  <div class="form-group">
    <%= f.text_field :name, class: 'form-control', placeholder: 'Enter Name' %>
  </div>

  <div class="form-group">
    <%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric (i.e. Miles, Pounds, $, Subscribers)' %>
  </div>

    <div class="date-group">
      <label> Date: </label>
      <%= f.date_select :date, :order => [:month, :year], class: 'date-select' %>
    </div>


<div class="america2">
  <%= button_tag(type: 'submit', class: "btn") do %>
  <span class="glyphicon glyphicon-plus"></span>
  <% end %>

  <%= link_to quantifieds_path, class: 'btn' do %>
  <span class="glyphicon glyphicon-chevron-left"></span>
  <% end %>

  <%= link_to @quantified, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn' do %>
  <span class="glyphicon glyphicon-trash"></span>
  <% end %>
</div>

</form>
</div>
<% end %>

  
  
<%= form_for(@result) do |f| %>
  <% if @result.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@result.errors.count, "error") %> prohibited this result from being saved:</h2>

      <ul>
      <% @result.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<div class="america">
<form>
  <div class="form-group">
    <%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
  </div>

    <div class="date-group">
      <label> Date: </label>
      <%= f.date_select :result_date, :order => [:month, :year], class: 'date-select' %>
    </div>


<div class="america2">
  <%= button_tag(type: 'submit', class: "btn") do %>
  <span class="glyphicon glyphicon-plus"></span>
  <% end %>

  <%= link_to results_path, class: 'btn' do %>
  <span class="glyphicon glyphicon-chevron-left"></span>
  <% end %>

  <%= link_to @result, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn' do %>
  <span class="glyphicon glyphicon-trash"></span>
  <% end %>
</div>

</form>
</div>
<% end %>

例如用户输入:

:name = Ran

:公制 = 英里

然后,此后每个月,他都会输入该月的平均里程数。如何在这两种形式之间建立关系?

:result_value = 2.1

:result_date = 一月

:result_value = 1.8

:result_date = 十二月

*每个名称/指标都有许多结果值/日期。

控制器

class QuantifiedsController < ApplicationController
  before_action :set_quantified, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
   @averaged_quantifieds = current_user.quantifieds.averaged
   @instance_quantifieds = current_user.quantifieds.instance
   @results = Result.all.order("result_date")
  end

  def show
  end

  def new
    @quantified = current_user.quantifieds.build
  end

  def edit
  end

  def create
    @quantified = current_user.quantifieds.build(quantified_params)
    if @quantified.save
      redirect_to quantifieds_url, notice: 'Goal was successfully created'
    else
      render action: 'new'
  end
end

  def update
    if @quantified.update(quantified_params)
      redirect_to quantifieds_url, notice: 'Goal was successfully updated'
    else
      render action: 'edit'
  end
end

  def destroy
    @quantified.destroy
    redirect_to quantifieds_url
  end

  private
    def set_quantified
      @quantified = Quantified.find(params[:id])
    end

    def correct_user
      @quantified = current_user.quantifieds.find_by(id: params[:id])
      redirect_to quantifieds_path, notice: "Not authorized to edit this goal" if @quantified.nil?
    end

    def quantified_params
      params.require(:quantified).permit(:categories, :name, :metric, :result, :date)
    end
end

class ResultsController < ApplicationController
  before_action :set_result, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]


  def index
   @results = Result.all.order("result_date")
  end

  def show
  end

  def new
    @result = current_user.results.build
  end

  def edit
  end

  def create
    @result = current_user.results.build(result_params)
    if @result.save
      redirect_to @result, notice: 'Goal was successfully created'
    else
      render action: 'new'
  end
end

  def update
    if @result.update(result_params)
      redirect_to @result, notice: 'Goal was successfully updated'
    else
      render action: 'edit'
  end
end


  def destroy
    @result.destroy
    redirect_to results_url
  end

  private
    def set_result
      @result = Result.find(params[:id])
    end

    def correct_user
      @result = current_user.results.find_by(id: params[:id])
      redirect_to results_path, notice: "Not authorized to edit this result" if @result.nil?
    end

    def result_params
      params.require(:result).permit(:result_value, :result_date)
    end
end

索引会变成这样,其中每个名称(指标)都有多个结果和日期:

我尝试执行这些说明,但我不断收到不同变体的不同错误:http://archive.railsforum.com/viewtopic.php?id=717

我也试过这个教程:http://railscasts.com/episodes/197-nested-model-form-part-2。但它有点过时了,所以我得到了一堆错误。

提前感谢您能给我的任何帮助!

【问题讨论】:

    标签: javascript ruby-on-rails ruby forms model


    【解决方案1】:

    你想要做的是 NestedAttributes 你可以阅读更多关于它http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    例子:

    # creates avatar_attributes=
    accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
    # creates avatar_attributes=
    accepts_nested_attributes_for :avatar, reject_if: :all_blank
    # creates avatar_attributes= and posts_attributes=
    accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
    

    这是类定义

    # File activerecord/lib/active_record/nested_attributes.rb, line 301
    def accepts_nested_attributes_for(*attr_names)
      options = { :allow_destroy => false, :update_only => false }
      options.update(attr_names.extract_options!)
      options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
      options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
    
      attr_names.each do |association_name|
        if reflection = _reflect_on_association(association_name)
          reflection.autosave = true
          add_autosave_association_callbacks(reflection)
    
          nested_attributes_options = self.nested_attributes_options.dup
          nested_attributes_options[association_name.to_sym] = options
          self.nested_attributes_options = nested_attributes_options
    
          type = (reflection.collection? ? :collection : :one_to_one)
          generate_association_writer(association_name, type)
        else
          raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
        end
      end
    end
    

    此外,如果您需要更多内容,还有一个来自 rails cast 的非常酷的视频来解释它http://railscasts.com/episodes/196-nested-model-form-part-1

    【讨论】:

      猜你喜欢
      • 2013-02-07
      • 2020-08-08
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多