I want to rewrite manual logic for updating a table to use nested attributes while using a third table to select multiple id values. This is my first time attempting this.
I have a MediaLibrary model. I have a PageTitle model which contains names. I have a MediaPage model which contains the id fields for MediaLibrary and PageTitle. I want to populate MediaPage using nested attributes. I want to create a collection_select for PageTitle which has the values that populate page_title_id MediaPage.
Here are my model definitions.
media_library.rb
has_many :media_pages, dependent: :destroy
accepts_nested_attributes_for :media_pages, allow_destroy: true
media_page.rb
belongs_to :media_library
validates :media_library_id, presence: true
validates :page_title_id, presence: true
page_title.rb
has_many :media_pages
My original view code when I was manually collecting the values is below.
<%= fields_for :media_pages do |media_page| %>
<%= media_page.label :media_page, "Page Titles" %><%= media_page.collection_select(:page_title_id, PageTitle.order("name"), :id, :name, {}, {multiple: true}) %>
<% end %>
Here is my current view:
<%= f.label :media_pages, "Page Titles" %>
<%= f.fields_for :media_pages do |media_page| %>
<%= media_page.collection_select(:page_title_id, PageTitle.order("name"), :id, :name, {}, {multiple: true}) %>
<% end %>
If I have more than one MediaPage row the view will show a collection_select list for each row. For example if I have two MediaPage rows I will see one collection_select list with the PageTitle name for the first record highlighted and a second collection_select list with the PageTitle name for the second record highlighted. As you can see the only things I changed from my first fields_for statement and the second one is (1) moving the label outside of the fields_for and (2) adding f.
I attempted something similar in Rails 3 Rails 3.2.13 - Delete Entry From Nested Attributes. When I attempted this in Rails 3 the collection_select only displayed one list with multiple rows highlighted. Since there was an issue with a blank array entry I decided to continue doing the manual process of updating the intermediate table.
What I want is to have one collection_select list displayed on my view where multiple PageTitle ids can be selected and populate the MediaPage table using nested attributes. If rows exist I want the corresponding PageTitle rows to be highlighted.
I have been trying to solve this for a long while. Through my research I have not found any examples where nested attributes were populated using a separate table.
Any help would be appreciated.