【问题标题】:Basic dashboard to manage posts in rails用于管理 Rails 中帖子的基本仪表板
【发布时间】:2014-06-06 05:30:13
【问题描述】:

我有一个使用 devise 进行身份验证的博客,用户可以在其中创建帖子,我创建了一个基本仪表板,用户可以在其中管理他们的帖子

这是我的仪表板控制器

before_action :authenticate_user!
def index
 @posts = Post.find(:all, :conditions => [ "user_id = ?", @current_user ]) 
end

这是我的仪表板视图

<% @posts.each do |post| %> 
 <%= post.content %> 
<% end %> 

这是我的用户模型

has_many :posts

还有我的帖子模型

belongs_to :user

这是我的 schema.rb

  create_table "posts", force: true do |t|
    t.text     "content"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

但是当我转到仪表板时,我没有收到任何帖子,当我将仪表板控制器更改为

def index
 @posts = Post.all
end

我正在收到所有帖子,所以有人可以告诉我我的错在哪里

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 devise dashboard


    【解决方案1】:

    find(:all, :conditions =&gt; []) 在 Rails 3.2 中已弃用。而是尝试:

    def index
      @posts = Post.where(:user_id => current_user)
    end
    

    另外,请确保您在控制器的 create 方法中添加了 user_id:

    def create
      @post = post.new(post_params)
      @post.user_id = current_user
    
      REST OF CODE GOES HERE
    end
    

    【讨论】:

    • 这个代码我得到了所有的帖子,但我只想得到我自己的帖子
    • 您确定您的帖子表中有 user_id 列吗?
    • 我不明白你的问题,请你详细说明
    • 是的,我几个小时前刚刚在我的帖子表中添加了一个 user_id:integer
    • 在您的仪表板视图页面上(您有代码&lt;% @posts.each,您可以将代码&lt;%= @posts %&gt; 放在某处并向我们展示@posts 的格式吗?看看会很有帮助跨度>
    【解决方案2】:

    替换

    @posts = Post.find(:all, :conditions =&gt; [ "user_id = ?", @current_user ])

    @posts = @current_user.posts

    【讨论】:

    • 我得到这个错误 undefined method `posts' for nil:NilClass 并且当我尝试这个 @posts = current_user.posts 我没有在视图中得到任何帖子
    • 不,我没有忘记,不过谢谢你的帮助
    猜你喜欢
    • 1970-01-01
    • 2019-09-01
    • 2016-07-02
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多