在两个实例对象之间创建关联 [英] Create association between two instancied objects

查看:140
本文介绍了在两个实例对象之间创建关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:(相册和产品)

I have two models: (Albums and Product)

1)内部模型

inside album.rb:

Inside album.rb:

class Album < ActiveRecord::Base
  attr_accessible :name
  has_many :products
end

内部product.rb:

Inside product.rb:

class Product < ActiveRecord::Base
  attr_accessible :img, :name, :price, :quantity
  belongs_to :album
end

2)使用" Rails控制台",如何设置关联(以便可以使用<%= Product.first.album.name%>")?

2) Using "rails console", how can I set the associations (so I can use "<%= Product.first.album.name %>")?

例如

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X" )
# what's next? how can i set the album and the product together?

推荐答案

您可以这样做:

a = Album.create( name: "My Album" )

p = Product.create( name: "Shampoo X" )
# OR
p = Product.create( name: "Shampoo X", album_id: a.id )
# OR
p.album = a
# OR
p.album_id = a.id
# OR 
a.products << a
# finish with a save of the object:
p.save

您可能必须将属性设置为产品模型上的album_id可以访问(不确定).

You may have to set the attribute accessible to album_id on the Product model (not sure about that).

还要检查@bdares的评论.

这篇关于在两个实例对象之间创建关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆