Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在Rails 4中将新闻id附加到评论中?_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何在Rails 4中将新闻id附加到评论中?

Ruby on rails 如何在Rails 4中将新闻id附加到评论中?,ruby-on-rails,Ruby On Rails,注释\u controller.rb: def create @comment = Comment.create(comment_params) if @comment.save redirect_to :back else redirect_to :back flash[:error] = @comment.errors.full_messages end end 新闻(u controller.rb): def show @news = News.find(params[

注释\u controller.rb:

 def create
@comment = Comment.create(comment_params)
if @comment.save
  redirect_to :back
else
  redirect_to :back
  flash[:error] = @comment.errors.full_messages
end
end
新闻(u controller.rb):

def show
  @news = News.find(params[:id])
  @comment =  @news.comments.new
end
comment.rb:

belongs_to :news, dependent: :destroy
新闻网:

has_many :comments
如果需要,我如何将新闻id附加到评论

@news = News.find(params[:id])
@comment = @news.comments.create(comment_params)
根本不起作用,因为

CommentsController#create Couldn't find News with 'id'=

您确定comment_params正在发送您期望的内容吗

它应该有正确的
news\u id

确保将
news
对象的id与用于创建注释的表单一起传递。这可以在
隐藏的\u字段中完成(如果您还没有这样做)。假设您使用的是form_helpers,如果您有:

f.hidden_field :news_id
然后新闻id应该正确地进入您的
CommentController

你可以做一个

`raise "Boom: #{comment_params}"`
在上面

@comment = Comment.create(comment_params)

以确保它的到来。只要提交一条评论,rails错误页面就会显示它得到的参数。

你的路线是什么?您可以嵌套将通过表单本身传递新闻id的资源:

resources :news do
  resources :comments
end
然后你可以做:

News.find(params[:news_id]).comments.create(comment_params)  

隐藏字段不是解决问题的方法,我不认为,让rails帮你解决吧。

yay,f.hidden\u field:news\u id有帮助