2015-02-03 7 views
0

Мне хотелось бы получить совет о моем коде, потому что я не очень хорошо использую ассоциацию has_many.has_many через несколько раз

В моем случае Пользователи могут отметить как просмотр сообщения. Они могут комментировать сообщения, а также могут писать заметки о сообщениях.

Это то, что я сделал:

class User 
    has_many :posts, through: post_views 
    has_many :posts, through: comments 
    has_many :posts, through: notes 
end 

class Post 
    has_many :users, through: post_views 
    has_many :users, through: comments 
    has_many :users, through: notes 
end 

class PostView 
    belongs_to: user 
    belongs_to: post 
end 

class Comment 
    belongs_to: user 
    belongs_to: post 
end 

class Note 
    belongs_to: user 
    belongs_to: post 
end 

Это нормально? Что я могу сделать, чтобы иметь лучший код?

Edit = после Mohammad AbuShady ответ класс User has_many: post_views has_many: viewed_posts, через:: post_views

has_many :comments 
    has_many :commented_posts, through: comments 

    has_many :notes 
    has_many :noted_posts, through: notes 
end 

class Post 
    has_many :post_views 
    has_many :viewer_users, through: post_views 

    has_many :comments 
    has_many :comments_users, through: comments 

    has_many :notes 
    has_many :notes_users, through: notes 
end 


class PostView 
    belongs_to: user 
    belongs_to: post 
end 

class Comment 
    belongs_to: user 
    belongs_to: post 
end 

class Note 
    belongs_to: user 
    belongs_to: post 
end 

нормально?

благодаря

Lokhi

ответ

0

Вы должны сделать связь с моделью присоединиться к through части к работе, так

class User < ActiveRecord::Base 
    has_many :post_views 
    has_many :viewed_posts, through: :post_views 
end 
class PostView < ActiveRecord::Base 
    belongs_to :posts 
    belongs_to :users 
end 
class Post < ActiveRecord::Base 
    has_many :post_views 
    has_many :users, through: :post_views 
end 

И то же самое для двух других моделей.

+0

нормально, если я хорошо понимаю, что я должен это делать – lokhi

Смежные вопросы