如何在1个表格中包含2个模型?

时间:2015-01-11 16:36:04

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

一个模型创建: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
&#13;
&#13;
&#13;

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

&#13;
&#13;
<%= 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 %>
&#13;
&#13;
&#13;

例如用户输入:

:name = Ran

:metric =里程

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

:result_value = 2.1

:result_date = January

:result_value = 1.8

:result_date = 12月

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

控制器

&#13;
&#13;
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
&#13;
&#13;
&#13;

&#13;
&#13;
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
&#13;
&#13;
&#13;

索引会像这样转变,每个名称(指标)会有多个结果和日期:

enter image description here

我尝试过实施这些说明,但我不断发现不同版本的错误:http://archive.railsforum.com/viewtopic.php?id=717

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

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

1 个答案:

答案 0 :(得分:2)

您要做的是 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