Model form within another model's form in Ruby on Rails -
i have content
model, playlist
model , bring together association in model called playlistitem
.
this how they're connected:
class content < activerecord::base has_many :playlist_items has_many :playlists, through: :playlist_items end class playlist < activerecord::base has_many :playlist_items, -> { order 'position asc' } has_many :contents, through: :playlist_items end class playlistitem < activerecord::base belongs_to :content belongs_to :playlist end
when edit playlist
, form shows field name
, that's attribute has. want able add together content
playlist
(in position
, that's playlistitem
s attribute) within form.
how can that?
this code have now:
<%= form_for(@playlist) |f| %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <%= f.fields_for :playlist_items |builder| %> <fieldset> <%= builder.label :content, "content id" %><br> <%= builder.text_area :content_id %> </fieldset> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %>
first, can allow playlist
model take nested attributes playlist_items
.
class playlist < activerecord::base has_many :playlist_items, -> { order 'position asc' } has_many :contents, through: :playlist_items accepts_nested_attributes_for :playlist_items end
then, can add together content_id
collection select, create drop downwards selection of contents each playlist item.
<%= f.fields_for :playlist_items |builder| %> <%= builder.label :position %><br> <%= builder.integer :position %><br> <%= builder.label :content %><br> <%= builder.collection_select :content_id, @contents, :id, :title, include_blank: 'please select' %> <% end %>
finally, in controller, you'll need allow playlist items attributes passed params, , set @contents
instance variable.
class playlistcontroller < applicationcontroller before_action :load_contents, only: [:new, :edit] def edit @playlist = playlist.find(params[:id]) # build 10 playlist_items added playlist 10.times do; @playlist.playlist_items.build; end end private def load_contents @contents = content.all # or query specific contents you'd end def playlist_params params.require(:playlist).permit(:name, playlist_items_attributes: [:id, :position, :content_id]) end end
remember you'll need build each playlist item you'd use. can in new
, edit
methods desire.
ruby-on-rails ruby forms model associations
No comments:
Post a Comment