问题描述
我在应用程序中为我的推文添加了注释,但是我在表单第一行的视图中看到此错误。
First argument in form cannot contain nil or be empty
Extracted source (around line #1): <%= form_for [@tweet,@comment] do |f| %>
我的路线
resources :tweets do
resources :comments
resources :likes
end
我的模特
class Comment < ApplicationRecord
belongs_to :tweet
belongs_to :user
end
我的控制器
class CommentsController < ApplicationController
def create
@tweet = Tweet.find(params[:id])
@comment = @tweet.comments.create(params[:comment].permit(:body))
redirect_to tweets_path
end
end
我的表格
comments/_form.html.erb
<%= form_for [@tweet,@comment] do |f| %>
<p><%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<br>
<br>
<%= f.submit %>
<% end %>
我的观点(部分)
tweets/_tweets_index.html.erb
<% @tweets.reverse.each do |tweet| %>
....
<%= render tweet.comments %><br>
Add a comment
<%= render partial: 'comments/form' %>
<% end %>
依次呈现到tweets / index.html.erb
<%= render partial: 'tweets_index' %>
我按照前面的问题在表格上更改了第一行.. [@ foo,@bar] ..如上所述,但仍然无法正常工作。我究竟做错了什么? ty
编辑:我已经取得了一些进步,但是出现了以下错误
我的表格
<%= form_for( :comment,:html => {:class => "form-horizontal",:role => "form"},url: tweets_path) do |form| %>
<p><%= form.label :body %><br>
<%= form.text_area :body %>
</p>
<br>
<br>
<%= form.submit %>
<% end %>
错误 :param丢失或值为空:tweet
def tweet_params
params.require(:tweet).permit(:user_id,:content,{ comments: [:body] })
end
{"authenticity_token"=>"79mdlyIOZTUF8hzXhoOpzTHKhk+/5SBrfnUjnImtmek1HyXDA0U/+R6oEOYgmy4H+a2kEppasDDKBobvdpbQdg==","comment"=>{"body"=>"Test"},"commit"=>"Save Comment"}
解决方法
该错误意味着@tweet
为nil。因此,无论您在何处呈现此表单,都要确保在相应的控制器操作中定义了@tweet
。