Rails3 has_and_belongs_to_many - 从连接表获取属性时出错
鉴于我有以下结构:
class A < ActiveRecord::Base
has_and_belongs_to_many :bs, :class_name => "B", :join_table => "ab"
end
class AB < ActiveRecord::Base
#ab has a date column "creation_date"
#ab also has a text column "creatior"
end
class B < ActiveRecord::Base
end
成功检索“creation_date”属性,
console> A.find(1).bs.first.creation_date
=> "14/08/1874"
我在控制器中
@a = A.find(1)
@bs = a.bs
但在视图(部分)中使用它,我收到以下错误
bs.each do |b|
b.b_attribute #this is O.K.
b.creation_date # cause error => undefined method `creation_date` for #<B:...>
end
# also try to debug in partial
A.find(1).bs.first.creation_date #=> this return data correctly
问题如上所示,可能会导致什么未定义的方法
,而直接属性仍然可以访问。
有人知道我的代码有什么问题吗?
Given that I have following structure:
class A < ActiveRecord::Base
has_and_belongs_to_many :bs, :class_name => "B", :join_table => "ab"
end
class AB < ActiveRecord::Base
#ab has a date column "creation_date"
#ab also has a text column "creatior"
end
class B < ActiveRecord::Base
end
I successfully retrieve "creation_date" attribute in rails console
console> A.find(1).bs.first.creation_date
=> "14/08/1874"
In controller
@a = A.find(1)
@bs = a.bs
But using it in a view (partial), I got following error
bs.each do |b|
b.b_attribute #this is O.K.
b.creation_date # cause error => undefined method `creation_date` for #<B:...>
end
# also try to debug in partial
A.find(1).bs.first.creation_date #=> this return data correctly
The problem as shown above, what can possibly cause undefined method
whilst the direct attributes are still accessible.
Anyone have any idea what is wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您处理中间模型时,不应使用
has_and_belongs_to_many
。该方法仅在连接表不是模型时才有效。您需要明确区分模型和表的概念。在 Rails 中,您很少能够访问底层表,大多数情况下您会处理包装模型。如果您的连接表除了
A
和B
的外键之外还有其他内容,并且您需要访问这些附加数据,那么它需要是一个模型。就您而言,确实如此,但您没有使用正确的关系。它应该看起来像这样:然后,访问
creation_date
和creator
应该通过AB
模型完成,因为它确实是属于它。请查看此处的示例快速解释:http://guides.rubyonrails.org/association_basics.html#choosing- Between-has_many-through-and-has_and_belongs_to_many
When you're dealing with an intermediate model, you shouldn't use
has_and_belongs_to_many
. That method works only when the join table is not a model. You need to make a clear distinction between the concepts of a model and a table. In rails, you rarely have access to the underlying table, most often you deal with the wrapping models.If your join table has anything more than the foreign keys to
A
andB
, and you need to access that additional data, then it needs to be a model. In your case, it is, but you're not using the correct relation. It should look like this:Afterwards, accessing
creation_date
andcreator
should be done through theAB
model, since it really is an attribute that belongs to it.Take a look here for a quick explanation with examples: http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many