[英]Ruby on Rails 'find' question
我目前正在使用:
@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
如果要為每個注釋輸出某些內容,請在視圖中使用循環
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.body %>
</div>
<% end %>
</div>
class User
has_many :posts
end
class Post
belonds_to :user
has_many :comments
end
class Comment
belongs_to :post
end
<h1>users contriller</h1>
@user = User.includes(:posts).where(:id => params[:id]).first
<h1>in posts view</h1>
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.name %>
</div>
<% end %>
</div>
<h1>in comment view</h1>
<div class="comments">
<% @user.posts.each do |p| %>
<div class="post">
<%= p.comments.body %>
</div>
<% end %>
</div>
當您可以更好地利用關聯時,不要自己發出查詢。
如果用戶has_many
帖子,並且帖子has_many
評論,則可以輕松完成。
user.posts
和
post.comments
另外,它看起來像用戶的has_many
注釋,因此您可以直接執行
user.comments
要從評論中獲取帖子ID,請在評論中添加一條belongs_to
帖子,然后可以執行以下操作:
comment.post.id # or comment.post.name directly
帖子有很多評論
和評論屬於帖子。 應該在發布和評論之間創建外鍵或粘合劑。
請記住,@ user的所有帖子都附有評論。
因此,要獲取評論ID,請從@ user.each.post({| post |
發表評論}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.