我在表单中添加了一个嵌套属性,嵌套属性的字段是教育字段不呈现,其他字段也是如此。关系似乎是有序的,控制器也是如此。
这是代码。
控制器
def new
@profile = current_user.build_student_profile
end
def profile_params
params.require(:student_profile).permit(:first_name, :last_name, :gender, student_profiles_attributes: [:degree, :university_id, :major, :major2, :start_date, :end_date, :grade, :grade_scale] )
end
模型
class Education < ActiveRecord::Base
belongs_to :student_profile
belongs_to :university
validates :grade_scale, inclusion: { in: %w(GPA4 GPA7 WAM100) }
validates :degree, :university_id, :major, :start_date, :end_date, :grade, :grade_scale, presence: true
end
class StudentProfile < ActiveRecord::Base
belongs_to :user
has_many :educations
validates :gender, inclusion: { in: %w(male female) }
validates :first_name, :last_name, :gender, presence: true
accepts_nested_attributes_for :educations
end
表格
<%= form_for (@profile) do |f| %>
<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%= f.label :last_name %>
<%= f.text_field :last_name %>
<%= f.label :gender %>
<%= f.text_field :gender %>
<%= f.fields_for :educations do |education_fields| %>
<%= education_fields.label :Degree %>
<%= education_fields.text_field :degree %>
<%= education_fields.label :University %>
<%= education_fields.collection_select(:university_id, University.all, :id, :name) %>
<%= education_fields.label :Major %>
<%= education_fields.text_field :major %>
<%= education_fields.label :Additional_Major %>
<%= education_fields.text_field :major2 %>
<%= education_fields.label :Start_Date %>
<%= education_fields.date_field :start_date %>
<%= education_fields.label :End_Date %>
<%= education_fields.date_field :end_date %>
<%= education_fields.label :Grade %>
<%= education_fields.number_field :grade %>
<%= education_fields.label :Grade_Scale %>
<%= education_fields.select :grade_scale, [["GPA / 4","GPA4"], ["GPA / 7","GPA7"], ["WAM / 100","WAM100"]] %>
<% end %>
<%= f.submit :submit %>
<% end %>
我尝试将以下内容添加到控制器新操作@profile.educations.build
但我收到错误未知属性student_profile_id
有人可以帮忙吗?
答案 0 :(得分:0)
确保student_profile_id
表中包含educations
属性/列。
之后,正如您所提到的,您需要在educations
上构建student_profile
对象:
def new
@profile = current_user.build_student_profile
@profile.educations.build
end
答案 1 :(得分:0)
试试这个
<%= f.fields_for(:educations,@profile.educations.build) do |education_fields| %>
<% end %>
或
def new
@profile = current_user.build_student_profile
@educations = @profile.educations.build
end
<%= f.fields_for(@educations) do |education_fields| %>
<% end %>