我在表单中添加了一个嵌套属性,嵌套属性的字段--即Education字段不呈现,其他字段则呈现。这些关系似乎是有序的,而控制器也是如此。
这是密码。
控制器
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
有人能帮忙吗?
发布于 2015-05-18 10:43:49
确保student_profile_id属性/列存在于educations表中。
在此之后,正如您已经提到的,您需要在educations上构建student_profile对象,如下所示:
def new
@profile = current_user.build_student_profile
@profile.educations.build
end发布于 2015-05-18 11:04:37
尝尝这个
<%= 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 %>
https://stackoverflow.com/questions/30301026
复制相似问题