[英]Joining multiple tables, fixing active record associations
我有多个桌子
行动:
id
line_id
devise_id
item_id
评论:
id
action_id
body
项目:
id
name
设计:
id
name
线:
id
name
型号:ActionModel:
belongs_to :devise, :foreign_key => 'devise_id'
belongs_to :item, :foreign_key => 'item_id'
belongs_to :line, :foreign_key => 'line_id'
has_many :comments
CommentModel:
belongs_to :action, :foreign_key => 'item_id'
has_many :items, through: :actions
ItemModel:
has_many :items, dependent: :destroy
has_many :devises, through: :actions
has_many :lines, through: :actions
设计模型:
has_many :actions, dependent: :destroy
has_many :items, through: :actions
has_many :lines, through: :actions
LineModel:
has_many :actions, dependent: :destroy
has_many :devises, through: :actions
has_many :lines, through: :actions
has_many :comments, through: :actions
在我的动作控制器中,我想要这样的东西:
def index
@actions = Action.joins(:item, :comment)
在我看来获取action.comment.body
和action.item.name
。
有人可以建议是否有任何办法吗?
您需要更改它,因为您的Comment
模型中已经有action_id
class Comment
belongs_to :action
end
您可以包括关联
@actions = Action.includes(:item, :comments)
它将获取所有评论和操作项。
你可以打电话
action.comments.each do |comment|
# Loop over the comments
comment.body
end
# and
action.item.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.