如何将model_id与第三级嵌套模型相关联?

时间:2017-12-14 12:26:11

标签: ruby-on-rails ruby-on-rails-5

我的模型结构看起来像这样

resources :genres do
  resources :stories do
     resources :episodes do
        resources :comments
     end
  end
end

我已经在评论表中添加了episode_id。然而,当我将genre_id和story_id添加到评论表并在控制台中检查它时,genre_id和story_id被赋予Nil。 `

Comment.rb

class Comment < ApplicationRecord
  belongs_to :episode
  belongs_to :story
  belongs_to :user
end

Genre.rb

class Genre < ApplicationRecord
  belongs_to :user
  has_many :stories, dependent: :destroy
end

Story.rb

class Story < ApplicationRecord
belongs_to :genre
belongs_to :user
has_many :comments
has_many :episodes, dependent: :destroy

has_attached_file :image, size: { less_than: 1.megabyte }, styles:{      medium: "300x300#", wide: "200x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

scope :of_followed_users, -> (following_users) { where user_id: following_users }

1 个答案:

答案 0 :(得分:0)

首先,如果没有设置otional: true,则无法将评论归因于更多模型,因为您的评论将需要所有关联模型的ID。

class Comment < ApplicationRecord
  belongs_to :episode, optional: true
  belongs_to :story, optional: true
  belongs_to :user
end

我很高兴你使用这个例子。

使用此迁移更改评论表

def change
  add_column :comments, :commentable_type, :string
  add_column :comments, :commentable_id, :integer
  add_column :comments, :user_id, :integer
end
class Comment < ApplicationRecord
  belongs_to :commentable,  polymorphic: true 
end
class User < ApplicationRecord
  has_many :comments
end
class Genre < ApplicationRecord
  ...
  has_many :comments, as: :commentable, depented: :destroy
end
class Story < ApplicationRecord
  ...
  has_many :comments, as: :commentable, depented: :destroy
end

现在你可以Story.last.comments.new =&gt; .., commentable_id: story_last_id, commentable_type: 'Story'

more about polymorphic associations