我怎样才能从我的观点中删除这个逻辑?
我正在努力解决这个问题。我知道视图中不应该有那么多逻辑。我有一个包含用户、帖子和评论的应用程序。用户有很多帖子和评论。
class User < ActiveRecord::Base
has_many :posts
has_many :comments
帖子属于用户并有很多评论。
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
评论属于用户和帖子
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
在我的帖子#show 视图中,我在帖子下显示评论。我想显示发表评论的用户的姓名。目前我的观点是:
<% @post.comments.each do |comment| %>
<p>
<b>Commenter:</b>
<%= link_to User.find(comment.userid).login, User.find(comment.userid) %>
</p>
<p>
<b>Comment:</b>
<%= comment.body %>
</p>
<% end %>
我应该在我的帖子控制器中拥有这种逻辑。但我很困惑。 @post.comments 返回属于该帖子的评论数组(?)。这意味着我不能拥有 @commenter = @post.comments.userid。我对这个问题感到困惑,所以我可能没有很好地解释它。
I am trying to wrap my head around this problem. I know views shouldn't have that much logic in them. I have an app with users, posts and comments. Users have many posts and comments.
class User < ActiveRecord::Base
has_many :posts
has_many :comments
Posts belong to users and have many comments.
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
Comments belong to users and posts
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
In my post#show view I show comments under the post. I want to show the name of the user who made the comment. At the moment I have this in my view:
<% @post.comments.each do |comment| %>
<p>
<b>Commenter:</b>
<%= link_to User.find(comment.userid).login, User.find(comment.userid) %>
</p>
<p>
<b>Comment:</b>
<%= comment.body %>
</p>
<% end %>
I should probably have that logic in my posts controller. But I am pretty confused. @post.comments returns an array(?) of comments belonging to the post. That means I can't have @commenter = @post.comments.userid. I am confused by the problem so I might not have explained it well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了更明确地表达第一个答案,您只需执行以下操作:
在您的 User 模型中,像这样重写 to_s 方法,以便 comment.user 返回您想要的字符串:
最后,使用急切加载在一个 SQL 调用中获取所有数据,而不是为每个 comment.user 单独查询数据库。在您的 Post 模型中:
在 Post 控制器中:
To be more explicit on the first answer, you simply do this:
In your User model, override the to_s method like this so comment.user returns the string you want:
Finally, use eager loading to get all the data in one SQL call, instead of querying the DB separately for each comment.user. In your Post model:
And in the Post controller:
事实上,在评论循环期间,您可以使用
comment.user
来获取用户的数据,因为您已经声明了User
has_many
评论
关系。In fact during the comments loop, you can use
comment.user
to get the data of the user since you have declared theUser
has_many
Comments
relationship.