【问题标题】:Display all posts by a single user in RAILS在 RAILS 中显示单个用户的所有帖子
【发布时间】:2011-11-24 03:07:59
【问题描述】:

我对 Rails 很陌生,我正在尝试在我的应用中显示用户发布的所有帖子。我确实在这个论坛上浏览过类似的帖子,但没有成功。我用 name 、 title 和 content 属性做了一些脚手架,然后创建了一个名为 Blogger 的模型,带有 'name' 属性。

这是我的代码

控制器

class BloggersController < ApplicationController

  def show
    @blogger = blogger.find(params[:id])
    @title = @blogger.name
    @posts = @blogger.posts
    respond_with(@posts)
  end
end

查看

Index.html.erb

<% @blogger.post.each do |post| %>
  post.name
  # Comments to the Post
  post.comments.each do |comment|
    comment.comments
 <% end %>

型号

class Post < ActiveRecord::Base
  validates :name, :presence=>true
  validates :title, :presence=>true
  has_many :comments
  belongs_to :blogger
  belongs_to :topic,    :touch => true
  accepts_nested_attributes_for :blogger
  attr_accessible :name, :title, :content
end

我收到“NoMethodError in Posts#index”错误提示

nil:NilClass 的未定义方法 `post' 并在提取的源代码中包含 index.htm.erb 的代码

【问题讨论】:

  • Blogger 课堂上有什么?非常重要,因为您尝试使用此模型处理帖子:>
  • 博主的名为“name”的字符串。每个博主都可以创建多个帖子。当我点击一个博主的名字时,我希望列出所有的帖子。感谢您的帮助
  • 您的整个班级Blogger 是一个名为name 的字符串?不确定这是否完全正确,因为您引用了 blogger.nameblogger.posts

标签: ruby-on-rails


【解决方案1】:

不是答案,只是一些指导原则:

您的问题代码中有很多错误。

@blogger = blogger.find(params[:id])

我觉得应该改成

@blogger = Blogger.find(params[:id])

接下来做一个

raise @blogger.inspect

并查看它是否已加载。

在您看来,您可以做得更好: (顺便说一句:如果你有 show 方法,它需要被称为 show.html.erb 而不是 index.html.erb)

#show html.erb

<%=render @blogger.posts %>

然后你在 posts/_post.html.erb 中创建一个文件

<%= post.name %>
<%= render post.comments %>

还有一个文件 comments/_comment.html.erb 用于呈现评论。

这是干燥的轨道方式!

【讨论】:

    【解决方案2】:

    也许是因为你把这段代码放在了 index.html.erb 因此,当您尝试显示此 HTML 页面时,rails 将尝试调用控制器中的方法 index,但您没有任何称为 index 的方法。 尝试将此代码放在名为 index / 的方法中,或尝试将 html.erb 文件的名称更改为 show.html.erb

    编辑:因此,在您的代码中,您传递了@posts 变量,但在您看来,您调用了@blogger.post。 它不应该被解决。您必须在将@blogger 或@posts 传递给您的视图之间进行选择,并且只使用您传递给视图的变量的属性。

    【讨论】:

      【解决方案3】:

      您正在寻找的错误是一个简单的错字,在您看来您应该写

      @blogger.posts.each
      

      而不是

      @blogger.post.each
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-02
        • 1970-01-01
        相关资源
        最近更新 更多