gpt4 book ai didi

ruby-on-rails - Ruby on Rails 'find' 问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:06 24 4
gpt4 key购买 nike

我目前正在使用:

@user = User.find(params[:id])
@posts = Post.find(:all, :conditions => ["user_id = ?", @user.id])
@comments = Comment.find(:all, :conditions => ["user_id = ?", @user.id])

它标识用户,并列出他们所做的所有评论。但是,我想设置一个局部变量以用于 _comment.html.erb 模板。我希望变量列出位于帖子表的“名称”列中的帖子名称。

我试过:

@post_id = @comments.post_id
@post_name = @post_id.name

但是它显示了一个数组错误(因为@comments 列出了用户评论的数组)。我需要找到一种方法来找到每条评论的 post_id。然而,当我尝试使用类似

@post_id = @comments.each.post_id

它显示错误,因为它没有将“post_id”识别为方法。我希望它为每条评论输出 post_id 列中的任何内容。

最佳答案

你的做法全错了。这个想法是使用关联,因此 Rails 将为您提供访问器。您应该只使用 find 来获取最顶层的记录。 Rails 将为您填充关联。

def User
has_many :posts
has_many :comments
end

def Post
belongs_to :user
end

您的代码将变为:

@user = User.find(params[:id])

# you can omit these and just use @user.posts and @user.comments in your view
@posts = @user.posts
@comments = @user.comments

如果你想为每个评论输出一些东西,那么在你的 View 中使用一个循环

<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.body %>
</div>
<% end %>
</div>

关于ruby-on-rails - Ruby on Rails 'find' 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3544474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com