2016-08-23 2 views
0

У меня есть несколько таблицОбъединение нескольких таблиц, фиксируя активные записи ассоциации

Действие:

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 

DeviseModel:

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 в моем Посмотреть.

Может ли кто-нибудь посоветовать, есть ли способ сделать это?

ответ

1

Вы должны изменить это, как вы уже action_id в вашей Comment модели

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 
+0

Я получил неопределенный метод 'комментария» для # <Действия: 0x0000000d987e18> – Geeedas

+0

ой мой плохой поступок имеет много комментариев –

+0

до [от моего ответа –