Search code examples
mysqlruby-on-railsformsform-helpers

rails 4 multiple models in one form including a key value table


I have a form that creates a "talent profile". In this form as a separate model are attributes "height, weight, hair, etc." for the talent profile. However, there are actually 4 tables involved in this.

Tables with examples
talent_profile
id - 1

talent_profile_attributes -(links the talent to an attribute with a value)
talent_id - 1
default_attribute_id - 2
default_attribute_value_id - 3

default_attributes -
id - 2
name - "hair"

default_atrribute_values -
id - 3
default_attribute_id - 2
value - "brown"

The relationships with the models are fine, I can insert into the table manually and retrieve the attributes for each profile as desired. However, the problem I am having is figuring out how to submit both the TalentProfile model, and the TalentProfileAttributes model in a single form.

I tried using accepts_nested_attributes_for, but have been unsuccessful. In addition I'm not quite sure how to approach getting the default_attribute_id and default_attribute_value_id into the fields of the form. Any ideas, or directions to go would be greatly appreciated, been researching this for a couple hours now to no avail.

Basically Im looking for a form that displays all the values from the DefaultAttributes table, with dropdowns including the DefaultAttributeValue for each attribute, and when submitted, creates the relationships in the TalentProfileAttribute table.


Solution

  • Figured it out, used this in the model, view and controller

    Model

    accepts_nested_attributes_for :talent_profile_attributes
    

    controller

    def new
      @talent = TalentProfile.new
      @attributes = DefaultAttribute.all
      @attributes.count.times { @talent.talent_profile_attributes.build }
    end
    

    View

    <% attr_i = DefaultAttribute.first.id - 1 %>
    <%= f.fields_for :talent_profile_attributes do |attrf| %>
      <%= attrf.label :default_attribute_value_id, @attributes[attr_i].name %>
      <%= attrf.select :default_attribute_value_id, 
                      @attributes[attr_i].default_attribute_values.collect {|p| [ p.value, p.id ] }.unshift("-") %> 
      <%= attrf.hidden_field :default_attribute_id, value: @attributes[attr_i].id %>
      <% attr_i += 1 %>
    <% end %>