ruby on rails - Adding only one record with nested attributes that is a has_many relationship -
i have been googling around day, , google-fu has seemed fail me. trying add/update single record has has_many relationship through nested attributes.
models:
class employee has_many :courses accepts_nested_attributes_for :courses, reject_if: :all_blank validates_associated :courses end class course belongs_to :employee validates :class_name, presence: true, length: { maximum: 60 } validates :class_date, presence: true end
controller:
def update @employee = employee.find(params[:id]) #... @employee.update_attributes(employee_params) #... end def employee_params params.require(:employee).permit(..., courses_attributes: [ :class_name, :class_date ]) end
view:
<%= empform.fields_for :courses |f| %> <%= f.label :class_name, "class name:" %> <%= f.text_field :class_name %><br /> <%= f.label :class_date, "class date:" %> <%= f.text_field :class_date %> <% end %>
the issue above code lists associated courses employee. not want. can do:
<%= empform.fields_for :courses, course.new |f| %> <!-- ... --> <% end %>
and display 1 field, , seems work far saving value db. however, if enter invalid data, validations fail. contents of text_field's empty. (because object new record , not invalid record.)
so, like:
controller:
def edit # ... @course = course.new end def update @employee = employee.find(params[:id]) @employee.update_attributes(employee_params) @course = @employee.courses.last if @employee.courses.last.new_record? end
then in view
<%= empform.fields_for :courses, @course %> <!-- .... --> <% end %>
but feels bit kludgy. guess wondering cleanest method/correct way is?
Comments
Post a Comment