Rap*_*ure 1 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2
我正在尝试为Post模型添加注释
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user #should this be has_one :user instead?
....
Run Code Online (Sandbox Code Playgroud)
如何设置我的注释new和创建操作以获取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
Run Code Online (Sandbox Code Playgroud)
视图
<%= form_for([@post, @post.comments.build]) do |f| %>
...
Run Code Online (Sandbox Code Playgroud)
然而,这似乎只是旨在与帖子相关联而不是用户.如何设置两个关联?
我假设你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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2543 次 |
| 最近记录: |