使用has_many创建新记录

时间:2014-08-18 14:43:21

标签: ruby-on-rails ruby-on-rails-4 has-many-through has-many

我正在尝试创建简单的表单来为特定商品(确切的备用艺术品)创建估价(优惠)。估价可能包含许多使用选择表格选择的部分。我正在使用下面列出的课程。我还创建了连接表valu_lines来存储估值。 使用表单时没有错误但缺少记录... 不幸的是,我陷入困境,不知道如何正确创建表单来保存valu_lines表中的记录?

我将非常感谢您对此问题的任何帮助!由于我是铁杆新手,因此我被困了两天,并且不知道如何克服这个......

class Valuation < ActiveRecord::Base
    has_many :valuation_lines
    has_many :parts, :through => :valuation_lines
    accepts_nested_attributes_for :parts
end

class ValuationLine < ActiveRecord::Base
    belongs_to :part
    belongs_to :valuation
end

class Part < ActiveRecord::Base
    has_many :valuation_lines
    has_many :valuations, :through => :valuation_lines
end

此外,我创建新估值的表格如下:

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

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

  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>

  <div class="field">
    <%= f.fields_for :part do |builder| %>
      <%= builder.label :part %><br>   
      <%= builder.collection_select :part_id, Part.all, :id, :name %>
    <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

加入表:

 create_table "valuation_lines", force: true do |t|
        t.integer "valuation_id"
        t.integer "part_id"
        t.integer "pruchase_price"
      end
估值控制人:

 # GET /valuations/new
  def new
    @valuation = Valuation.new
  end

   # POST /valuations
  # POST /valuations.json
  def create
    @valuation = Valuation.new(valuation_params)

    respond_to do |format|
      if @valuation.save
        format.html { redirect_to @valuation, notice: 'Valuation was successfully created.' }
        format.json { render action: 'show', status: :created, location: @valuation }
      else
        format.html { render action: 'new' }
        format.json { render json: @valuation.errors, status: :unprocessable_entity }
      end
    end
  end

0 个答案:

没有答案
相关问题