使用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>
什麼是去了解這一點的最好方法是什麼?
它不應該是** **職位是 – Abhi