这就是我将Micropost发布为current_user
(Devise)的方式:
microposts_controller.rb:
def create
@user = current_user
@micropost = @user.microposts.new(params[:micropost])
@micropost.save
redirect_to @micropost
end
这是我在微博中发表评论的方式:
comments_controller.rb:
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.create(params[:comment])
redirect_to micropost_path(@micropost)
end
现在我想发表评论current_user
为了实现这个目的,有什么建议吗?
微柱/ show.html.erb
<h2>Add a comment:</h2>
<%= form_for([@micropost, @micropost.comments.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
编辑:
不确定是否需要看到这个,但以下是模型:
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :micropost
belongs_to :user
end
micropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :title, :content
belongs_to :user
has_many :comments
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :microposts
has_many :comments
end
答案 0 :(得分:2)
在comments_controller中尝试这个:
def create
@micropost = Micropost.find(params[:micropost_id])
comment_attr = params[:comment].merge :user_id => current_user.id
@comment = @micropost.comments.create(comment_attr)
redirect_to micropost_path(@micropost)
end
到目前为止,我认为您的评论没有附加用户..
编辑 - 我更改了:用户为:user_id。更有意义,因为我们还没有评论。