2012-01-29 57 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