我在 Rails 4.1.0.beta 上创建了一个简单的多对一关系
项目.rb
class Item < ActiveRecord::Base
belongs_to :owner, :class_name => "User"
belongs_to :category
has_many :sales
accepts_nested_attributes_for :sales
validates_presence_of :category, :owner, :name, :description
end
销售.rb
class Sale < ActiveRecord::Base
belongs_to :item
belongs_to :seller, :class_name => "User"
has_many :bids
validates_presence_of :item, :seller
end
这些是根据schema.rb在数据库中的相关表
create_table "items", force: true do |t|
t.integer "owner_id"
t.integer "category_id"
t.string "name"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "sales", force: true do |t|
t.integer "item_id"
t.integer "seller_id"
t.integer "buy_it_now"
t.boolean "bidding_enabled"
t.integer "minimum_starting_bid"
t.string "currency"
t.datetime "created_at"
t.datetime "updated_at"
end
在 Rails 控制台中,当我尝试创建嵌套在 Item 中的 Sale 时,如下所示:
> params = {"item"=>{"owner_id"=>"3", "category_id"=>"1", "name"=>"fawkin item", "description"=>"blarg", "sales_attributes"=>{"0"=>{"seller_id"=>"3", "buy_it_now"=>"5", "bidding_enabled"=>"0", "minimum_starting_bid"=>"", "currency"=>"btc"}}}}
> item = Item.new(params["item"])
> item.sales.first
item.sales 中生成的销售条目缺少 item_id:
#<Sale id: nil, item_id: nil, seller_id: 3, buy_it_now: 5, bidding_enabled: false, minimum_starting_bid: nil, currency: "btc", created_at: nil, updated_at: nil>
如果我尝试保存项目,事务会回滚:
> item.save
> item.errors
#<ActiveModel::Errors:0x000000013bfc58 @base=#<Item id: nil, owner_id: 3, category_id: 1, name: "fawkin item", description: "blarg", created_at: nil, updated_at: nil>, @messages={:"sales.item"=>["can't be blank"]}>