保存嵌套fields_for ..错误消息<xxx>的Rails 5必须存在

时间:2017-01-19 22:19:39

标签: ruby-on-rails fields-for nested-form-for

我有以下型号:

class Person < ApplicationRecord
  has_many :interests, dependent: :destroy
  accepts_nested_attributes_for :interests

  validates_presence_of  :email
  validates_inclusion_of :gender, :in => %w(M F), message: "Gender can     only be in M or F"
  has_secure_password

  def name
    "#{first_name} #{last_name}"
  end

  def interests_concatenated
    interests.map { |i| i.interest }.join(", ")
  end
end

class Interest < ApplicationRecord
  belongs_to :person
end

我的控制器如下:

class PeopleController < ApplicationController

def index
  @person = Person.all
end

def new
  @person = Person.new
  @person.interests.build
end

def create
  @person = Person.new(people_params)
  if @person.save
    session[:user_id] = @person.id
    redirect_to(people_path)
  else
    flash = "Email or gender can't be blank!"
    render 'new'
  end
end

private
  def people_params
    params.require(:person).permit(:email, :first_name, :last_name, :gender, :password,:password_confirmation, interests_attributes: [:hobby])
  end
end

我的表格如下:

<%= form_for @person  do |f| %>
<p>
  <%= f.label :email %> <br>
  <%= f.text_field :email %>
</p>
<p>
  <%= f.label :first_name %> <br>
  <%= f.text_field :first_name %>
</p>
<p>
  <%= f.label :last_name %> <br>
  <%= f.text_field :last_name %>
</p>
<p>
  <%= f.label :gender %> <br>
  <%= f.label(:gender_male, "Male") %>
  <%= f.radio_button(:gender, "M") %> <br>
  <%= f.label(:gender_female, "Female") %>
  <%= f.radio_button(:gender, "F") %> <br>
</p>
<p>
  <%= f.label :password %> <br>
  <%= f.password_field :password %>
</p>
<p>
  <%= f.label :password_confirmation %> <br>
  <%= f.password_field :password_confirmation %>
</p>
<p>
  <%= f.fields_for :interests do |i| %>
    <%= i.label :hobby %>
    <%= i.text_field :hobby  %>
  <% end %>
</p>
<p>
  <%= f.submit %>
</p>
<% end %>

以下是运行它时的byebug控制台日志:

console error message

非常难过为什么它不起作用。这可能与参数有关吗?

这是我提交表单时的日志文件:

enter image description here

2 个答案:

答案 0 :(得分:2)

而不是:

@interests = @person.interests.new

@interests = @person.interests.build

new创建一个全新的,干净的,完全空的新对象......但build是特殊的Rails关联方法,它将使用适当的默认值填充它(例如,右{{1} })

答案 1 :(得分:0)

我在我的兴趣模型中添加了这个解决方案:

class Interest < ApplicationRecord
  belongs_to :person, **optional: true**
end

由于@person每次都无法保存,最大的线索是错误消息“兴趣人必须存在”,我发现this StackOverflow solution有帮助。此blog post on why this is needed也有助于阐明这个问题。

感谢所有重视的人!