Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails中嵌套模型的建模_Ruby On Rails_Ruby_Database - Fatal编程技术网

Ruby on rails rails中嵌套模型的建模

Ruby on rails rails中嵌套模型的建模,ruby-on-rails,ruby,database,Ruby On Rails,Ruby,Database,我一直在努力解决一个很难解决的问题。我有一个用户模型,一个照片模型和一个评论模型。现在我的网站的工作方式是,一个用户可以对一张特定的照片有很多评论。相反,评论只能属于特定照片上的特定用户 我已经阅读了活动记录关联文档,从我收集的信息来看,我们不能使用has\u many:through关联,因为它似乎适用于模型之间的多态关联。我想知道一个人是否可以使用has\u many:throughassociation在一边,而属于association在另一边 有什么提示、建议和建议吗?我刚刚开始学习R

我一直在努力解决一个很难解决的问题。我有一个用户模型,一个照片模型和一个评论模型。现在我的网站的工作方式是,一个用户可以对一张特定的照片有很多评论。相反,评论只能属于特定照片上的特定用户

我已经阅读了活动记录关联文档,从我收集的信息来看,我们不能使用
has\u many:through
关联,因为它似乎适用于模型之间的多态关联。我想知道一个人是否可以使用
has\u many:through
association在一边,而
属于
association在另一边

有什么提示、建议和建议吗?我刚刚开始学习RubyonRails

谢谢。

这样行吗

class User
  has_many :photos
  has_many :comments
end

class Photo
  belongs_to :user
  has_many :comments
end

class Comment
  belongs_to :user
  belongs_to :photo
end

用户有许多照片和评论(他上传/写的),每个评论都属于用户(作者)和一张被评论的照片。

您可以这样做:

User 
 has_many :comments

Photo
  has_many :comments
  belongs_to :user

Comment
  belongs_to :user
  belongs_to :photo

这应该可以解决问题。我刚刚完成了完全相同的代码示例的编写!:但是什么时候应该通过关联使用多个?如何使用这些关联访问注释?您可以使用
has\u many
through
选项来指定关联表。你可以找到更多的细节,以及如何访问评论?哇,多棒的回答啊。我现在就试试,然后再给你回复。你能解释一下当前用户的
方法是如何工作的吗?更具体地说,我们在
where user\u id:self.user\u id
中做什么?它应该挑出制作照片的用户所写的任何评论。也就是说,评论的
用户id
=
照片。用户id
但是许多不同的用户可以对照片发表评论,所以这不会妨碍其他用户发表评论吗?不,他们可以随心所欲地发表评论。该方法旨在为您提供一种仅显示照片用户的评论的方法。无论你是否使用它,它都是完全可选的
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :photos
   has_many :comments, through: :photos #-> probably won't work but I'd try it first
end

#app/models/photo.rb
class Photo < ActiveRecord::Base
   belongs_to :user
   has_many :comments do
       def current_user #-> photo.comments.current_user
          where user_id: self.user_id
       end
   end
end 

#app/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :photo
   belongs_to :user
end
<% @user.photos.each do |photo| %>
   <%= photo.comments.each do |comment| %>
      <%= comment %>
   <% end %>
<% end %>
<% @user.photos.each do |photo| %>
   <%= photo.comments.current_user.each do |comment| %>
      <%= comment %> #-> comments where user_id will be the same as photo's user_id
   <% end %>
<% end %>