class Comment < ActiveRecord::Base belongs_to :post belongs_to :user end
因此,通过以上的关联,我可以从一个给定的注释对象中获取用户和发布细节吗?。 喜欢
@comment.post.post_title and @comment.user.user_name.
另外,请注意,我已经使用注释作为post的嵌套资源。
resources :posts do resources :comments end
是的,您可以这样做,并且不需要指定外键或类名。说 belongs_to :user 意味着rails将在comments表中查找user_id integer字段,并期望存在名为user的activeRecord类。
belongs_to :user
你想加多少就加多少,它们不会互相干扰。