mercredi 31 août 2016

rails struggle to make nested form work

i have 3 models,

the relationship between those models is many to many relationship.

unit model

  has_many :unitrentperiods, inverse_of: :unit
  has_many :rentperiods, :through => :unitrentperiods

unitrentperiod model

   belongs_to :unit
   belongs_to :rentperiod

rentperiod model

   has_many :unitrentperiods, inverse_of: :rentperiod
   has_many :units, :through => :unitrentperiods

and i have a unit form, where i can create a new unit or edit an unit. i want to make my unit form not just able to manage my unit but able to manage my "unitrentperiod" as well, so lets say i have 2 rent periods like

"6 months"
"12 months"

i want my unit form to display those rent periods also with price input, so when i save my unit form, i also save 2 unitrentperiod based on rent periods in database, i did this in my view :

           <% @rentperiods.each do |rentperiod| -%>
                <tr>
                    <td><%= rentperiod.rentmonth %></td> Month
                    <td>
                          <%= f.fields_for :unitrentperiods, rentperiod.unitrentperiod.build do |element| -%>
                          <%= element.text_field :rentprice %> IDR

                          <% end -%>
                    </td>
                </tr>
          <% end -%>

somehow it's not working.

Aucun commentaire:

Enregistrer un commentaire