ruby on rails - How to create an ActiveRecord object with a many-to-many relationship -
i have created blank rails app (rails new cheese_shop
), 2 models , bring together table. trying create cheese shop , specifying cheeses contains, @ creation time, this:
cheeses = [ cheese.create!(name: "bree"), cheese.create!(name: "kaĨkavalj"), ] shop.create! name: "the whistling cheese", cheeses: cheeses
however, i'm getting error:
sqlite3::constraintexception: not null constraint failed: stocks.shop_id: insert "stocks" ("cheese_id", "created_at", "updated_at") values (?, ?, ?)
apparently, shop id not inserted stocks
table when create shop. possible prepare this, without having in 2 steps (i.e. without first creating shop, , adding cheeses?)
class cheese < activerecord::base has_many :shops, through: :stocks has_many :stocks end class shop < activerecord::base has_many :cheeses, through: :stocks has_many :stocks end class stock < activerecord::base belongs_to :shop belongs_to :cheese end
my migrations this: class="lang-rb prettyprint-override">class createtables < activerecord::migration def alter create_table :cheeses |t| t.string :name, null: false t.timestamps null: false end create_table :shops |t| t.string :name, null: false t.timestamps null: false end create_table :stocks |t| t.integer :shop_id, null: false t.integer :cheese_id, null: false t.integer :amount t.float :price end end end
maybe should seek utilize nested attributes:
class shop < activerecord::base has_many :cheeses, through: :stocks has_many :stocks accepts_nested_attributes_for :stocks end
and able like:
cheese = cheese.create!(name: "bree") params = { attrib: { name: "the whistling cheese", stocks_attributes: { cheese_id: cheese.id} } } shop.create params[:attrib]
here doc: http://api.rubyonrails.org/classes/activerecord/nestedattributes/classmethods.html
ruby-on-rails ruby activerecord many-to-many
No comments:
Post a Comment