2015-05-16 25 views
1

使用Rails 4與Devise將用戶ID分配給嵌套模型

我有一個Post模型和一個評論模型。評論嵌套在帖子中。我已將帖子分配給用戶,但由於嵌套而無法將註釋分配給用戶。

的routes.rb

resources :posts do 
    resources :comments 
end 

user.rb

has_many :posts 
has_many :comments 

post.rb:

has_many :comments 
belongs_to :user 

comment.rb:

belongs_to :post 
belongs_to :user 

在我comments_controller.rb我一直在使用CURRENT_USER這樣的嘗試:

def new 
    post = Post.find(params[:post_id] 
    @comment = current_user.post.comments.build 

    respond_to do |format| 
    format.html # new.html.erb 
    format.xml { render :xml => @comment } 
    end 
end 

def create 
    post = Post.find(params[:post_id]) 
    @comment = current_user.post.comments.create(comment_params) 

    respond_to do |format| 
     if @comment.save 
     format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') } 
     format.xml { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

,但我收到此錯誤:

undefined method `post' for #<User:0x00000103300a30> 

什麼是去了解這一點的最好方法是什麼?

+1

它不應該是** **職位是 – Abhi

回答

1
@comment = post.comments.build 

代替

@comment = current_user.post.comments.build 

它不喜歡的工作。

你已經告訴它什麼post是如此你期望current_user.post返回不同的東西?

def create 
    post = Post.find(params[:post_id]) 
    @comment = post.comments.create(comment_params) 
    @comment.user = current_user 

    respond_to do |format| 
    if @comment.save 
     format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') } 
     format.xml { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

,而不是

def create 
    post = Post.find(params[:post_id]) 
    @comment = current_user.post.comments.create(comment_params) 

    respond_to do |format| 
    if @comment.save 
     format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') } 
     format.xml { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } 
    end 
    end 
end 
+0

你是對的。我如何將評論分配給用戶? – Kathan

+0

真棒謝謝你。我是否也需要在新動作中包含'@comment.user = current_user'?我不認爲我會做,但只是確保。我很抱歉,我是新來的鐵軌,仍然需要閱讀導軌指南。 – Kathan

+1

不用擔心。你是正確的,current_user在服務器端是已知的,所以沒有把它放在新的動作中。 – daslicious