这就是我如何将微博发布为current_user (设计,设计)的方式:
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的形式发表一条评论
为了做到这一点,有什么建议吗?
microposts/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
endmicropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :title, :content
belongs_to :user
has_many :comments
enduser.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发布于 2012-01-29 12:05:01
在你的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。更有意义,因为我们还没有评论。
https://stackoverflow.com/questions/9052809
复制相似问题