代码之家  ›  专栏  ›  技术社区  ›  hohner

rubyonrails“查找”问题

  •  1
  • hohner  · 技术社区  · 16 年前

    我目前正在使用:

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

    它标识用户,并列出他们的所有评论。但是,我想设置一个局部变量,以便在_注释.html.erb模板。我想让变量列出post表的'name'列中的post名称。

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

    但是它显示了一个数组错误(因为@comments列出了用户注释的数组)。我需要找到一种方法,能够找到每个评论后的id。但是当我尝试使用

    @post_id = @comments.each.post_id
    

    它显示了一个错误,因为它没有将“post\u id”识别为一个方法。我希望它为每个评论输出post\u id列中的内容。

    4 回复  |  直到 16 年前
        1
  •  5
  •   user229044    16 年前

    你完全搞错了。其思想是使用关联,以便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>
    
        2
  •  1
  •   Anurag    16 年前

    如果用户 has_many 岗位,岗位 你有很多 评论,你可以简单的做。

    user.posts
    

    post.comments
    

    你有很多

    user.comments
    

    要从评论中获取post id,请发表评论 belongs_to 一篇文章,然后你可以做:

    comment.post.id # or comment.post.name directly
    
        3
  •  1
  •   chandrasekhar    11 年前
    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>
    
        4
  •  0
  •   roydell Clarke    14 年前

    帖子有很多评论

    评论属于帖子。应该在post和comment之间创建外键或粘合剂。

    请记住,@user拥有所有附有评论的帖子。

    发布评论}