rails中的连接表有问题

时间:2011-08-11 16:28:33

标签: ruby-on-rails-3

我有一个连接作者和产品的连接模型。这叫做合同。我想在创建产品后立即创建合同,因此在我的产品模型中,我有:

     after_save :create_contract

     def create_contract
        contract = Contract.new(
          :product_id => self.id,
          :author_id => @author_id
        )
        contract.save   
     end

这对我来说似乎很简单,但是:当它准备进入数据库时​​,author_id总是出现nil。我尝试了几种不同的设置方法,似乎没什么用。我猜这与我如何使用产品表单提交相关,如下所示:

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

    <div>
        <%= collection_select( "contract", "author_id", @authors, "id", "full_name") %>
    </div>

在控制器中:

  def create
    @author_id = params[:contract][:author_id]
    @product = Product.new(params[:product])
    ...
  end

这是我在日志中看到的内容。

Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "product"=>{"title"=>"", "handle"=>"", "description"=>"", "keywords"=>""}, "contract"=>{"author_id"=>"1"}, "commit"=>"Create Product"}
  SQL (1.1ms)  INSERT INTO "products" ("created_at", "description", "handle", "keywords", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", Mon, 08 Aug 2011 04:37:09 UTC +00:00], ["description", ""], ["handle", ""], ["keywords", ""], ["title", ""], ["updated_at", Mon, 08 Aug 2011 04:37:09 UTC +00:00]]
  SQL (0.7ms)  INSERT INTO "contracts" ("author_id", "created_at", "product_id", "updated_at") VALUES (?, ?, ?, ?)  [["author_id", nil], ["created_at", Mon, 08 Aug 2011 04:37:09 UTC +00:00], ["product_id", 5], ["updated_at", Mon, 08 Aug 2011 04:37:09 UTC +00:00]]

关于问题所在的任何想法?

class Product < ActiveRecord::Base
  has_many :authors, :through => :contracts

class Author < ActiveRecord::Base
  has_many :products, :through => :contracts

class Contract < ActiveRecord::Base
  belongs_to :author
  belongs_to :product
end

2 个答案:

答案 0 :(得分:1)

所以,jimworm's nested_attributes有效,有两处变化:

<%= f.fields_for :contract do |c| %>
  <%= c.collection_select :author_id, Author.all, :id, :name %>
<% end %>

(假设<%= form_for(@product) do |f| %>

然后,在产品控制器中:

def new
    @product = Product.new
    contract = @product.contracts.build
 ...

答案 1 :(得分:0)

@author_id create_contract中的Productclass Product < ActiveRecord::Base has_one :contract, :dependent => :destroy has_one :author, :through => :contract accepts_nested_attributes_for :contract end class Contract < ActiveRecord::Base belongs_to :product belongs_to :author end class Author < ActiveRecord::Base has_many :contracts, :dependent => :destroy has_many :products, :through => :contracts end 模型,因此与您的控制器的范围不同。

尝试在模型中添加以下内容:

...
<%= f.fields_for :contract do |c| %>
  <%= c.collection_select :author_id, Author.all, :id, :name %>
<% end %>
...

然后以你的形式:

{{1}}

试一下,看看它是怎么回事。