【问题标题】:Comments that belong_to Post and belong_to User属于 Post 和 belongs_to User 的评论
【发布时间】:2012-04-05 22:36:18
【问题描述】:

我正在尝试将 cmets 添加到 Post 模型中

class Comment < ActiveRecord::Base
    belongs_to :post
    belongs_to :user #should this be has_one :user instead?
....

如何设置我的新评论和创建操作以获取 current_user 和当前帖子?

guides.rubyonrails.org 建议

控制器:

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
end

查看

<%= form_for([@post, @post.comments.build]) do |f| %>
...

然而,这似乎只是为了与帖子相关联,而不是与用户相关联。如何设置这两个关联?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    我假设您的控制器中某处有一个 current_user() 方法。

    所以应该这样做:

    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.build(params[:comment])
        @comment.user = current_user
        @comment.save
        redirect_to post_path(@post)
    end
    

    【讨论】:

    • 并且表单应该像这样构建: 而不仅仅是 ?
    • 谢谢!我能够实现这个!
    【解决方案2】:

    Deradon 很好地回答了这个问题,但我更喜欢在新的评论表单本身中包含这种逻辑。例如,不用调用这些变量,您可以:

    app/views/cmets/_form.html.erb:

    <%= f.hidden_field :user_id, value: current_user.id %>
    <%= f.hidden_field :post_id, value: @post.id %>
    

    这当然假设您的新评论表单嵌入在“发布展示”页面中,因此@post 可用:

    app/views/posts/show.html.erb:

    <body>
      <%= render @post %>
      <%= render 'comments/_form' %>
    </body>
    

    这会将 post_id 和 user_id 直接添加到数据库中以获取新评论。此外,不要忘记为这些外键创建索引,以便数据库可以更快地访问。如果你不知道怎么做,谷歌它!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多