我有一個將作者連接到產品的連接模型。這就是合同。我想盡快創建產品創建的合同,所以在我的產品型號,我有:在導軌中連接表的問題
after_save :create_contract
def create_contract
contract = Contract.new(
:product_id => self.id,
:author_id => @author_id
)
contract.save
end
在我看來很簡單,但:AUTHOR_ID總是出現零時,它已經準備好進入數據庫。我嘗試了幾種不同的方式來設置它,似乎沒有任何工作。我猜它涉及到如何我的產品形式,它看起來像這樣在提交:
<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>
和Controller:
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
,我想補充一點,當我直接在模型中設置author_id時,與實例變量相反,它仍然是零。 – Slick23
如果你想更新它,你可以編輯你的問題:)你能展示你製作的完整模型,還是隻展示你是如何建立它們之間的關聯(如果它們太大)?我想那邊有什麼問題。 – Veger
這只是更快點擊評論按鈕。我已經添加了關聯。 – Slick23