Ruby on rails 如何在连接模型中使用Rails访问信息
我有两种型号:Ruby on rails 如何在连接模型中使用Rails访问信息,ruby-on-rails,join,has-and-belongs-to-many,Ruby On Rails,Join,Has And Belongs To Many,我有两种型号: USERS has_many :celebrations has_many :boards, :through => :celebrations BOARDS has_many :celebrations has_many :users, :through => :celebrations CELEBRATIONS :belongs_to :user :belongs_to :board 我知道我创建了第三个连接表和模型,称为“庆祝”,它不需要ID cr
USERS
has_many :celebrations
has_many :boards, :through => :celebrations
BOARDS
has_many :celebrations
has_many :users, :through => :celebrations
CELEBRATIONS
:belongs_to :user
:belongs_to :board
我知道我创建了第三个连接表和模型,称为“庆祝”,它不需要ID
create_table :, :id => false do |t|
t.column :board_id, :int, :null => false
t.column :user_id, :int, :null => false
t.column :role, :string, :null => false
t.column :token, :string
t.timestamps
end
end
我如何获取这些信息
用户角色
user.celeerations.token
用户板
董事会用户
提前谢谢。我理解这是一个真正的新手问题。是的,您可以,但是如果联接表具有附加属性,那么您应该将其转换为完整模型。我想用
id、article\u id、author\u id
和其他字段(如role
)创建一个新的Rails模型
这就是Rails实现这些事情的方式。使联接表稍微大一点会有一点开销。但是,对于完全连接模型,可以使用标准Rails函数来创建和更新该模型
据我所知,添加了
has-many:through
选项以支持更好的连接模型。对于has-many:through
,您需要具有id
(主键)(对于HABTM,您不需要)。要访问信息,您定义的内容是正确的(user.certifications.role
,user.celeerations.token
,user.boards
,board.users
)。从迁移中删除:id=>false
。您也可以在迁移中说t.string:role
而不是t.column:role,:string
。谢谢,我会按照您的建议做。谢谢你的回复。这真的很有帮助。在编写连接表时,我不确定是否要将其ID去掉。现在我明白我需要它。谢谢你的帮助。