2012-01-29 60 views
0

这是我发表的微柱current_userDevise):在微博中发布评论为'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

你是如何设定的新注释'user'属性?它不是attr_accessiable – yoavmatchulsky 2012-01-29 12:02:19

+0

@yoavmatchulsky对不起,我改变了这一切。评论有一个'user_id'属性。 – alexchenco 2012-01-29 12:05:53

回答

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为:user_id。更有意义,因为我们还没有评论。

+0

感谢您的帮助,但我得到这个:'数据库被锁定。 app/controllers/comments_controller.rb:22:在'create'中。 { “UTF8”=> “✓”, “authenticity_token”=> “ciwlksY + xXnS6zW6xwAGayK3N/5lhRwTa1pa5x9SYOg =”, “注释”=> { “内容”=> “ssadasd”}, “提交”=> “创建注释” “micropost_id” =>“3”}' – alexchenco 2012-01-29 12:11:02

+0

没关系只需要重新启动服务器。非常感谢! – alexchenco 2012-01-29 12:13:23