由于某种原因,该表格似乎可以按预期工作,但无法正确处理:
这是发送到我的Paragraph#create方法的参数
Parameters: {"utf8"=>"✓", "authenticity_token"=>"s6V7WS6NZwcu4ZAeSenkEgVEd6MrrDD1asMjPEOuZHyglMKoGQ/5cP/USzF/5MJV3wyFn+siC2t47dSFkVtuVQ==", "paragraph"=>{"sentiments_attributes"=>{"0"=>{"body"=>"test"}}}}
我尝试提交表单时遇到此错误:Sentiments body can't be blank
#paragraphs_controller.rb
def create
@paragraph = Paragraph.new(paragraph_params)
@paragraph.sentiments.build
if @paragraph.save
redirect_to root_url
else
puts @paragraph.errors.full_messages
redirect_to root_url
end
end
private
def paragraph_params
params.require(:paragraph).permit(:sentiments_attributes => [:body])
end
我有2个模型,情感和段落。本段是情绪的集合。因此,如果我有一个用于创建新段落的表格,它将同时创建一种情感。
class Sentiment < ApplicationRecord
belongs_to :paragraph, optional: true
validates :body, presence: true
end
class Paragraph < ApplicationRecord
has_many :sentiments
accepts_nested_attributes_for :sentiments
end
<%= form_for(@paragraph) do |f| %>
<%= f.fields_for :sentiments do |u| %>
<%= u.text_area :body %>
<% end %>
<%= f.submit %>
<% end %>
已更新
需要从@paragraph.sentiments.build
删除paragraphs_controller#create
答案 0 :(得分:0)
需要从parasss_controller#create中删除@ paragraph.sentiments.build