Rails collection_select form adds selected value to an array -


i have rails 4 app game database. models relevant question are:

  • game
  • genre
  • gamegenre (the relationship table)

it has games/new form, creates new game records.

within form, want sub-form allows user add genres. envision working follows:

  1. the user selects genre select input. options populated genre.all
  2. when user hits add button, id of selected genre pushed array. can add many genres want array.
  3. when user hits save on main game form, app uses add_genre function i've defined create gamegenre relationship records each of genres.

this games/new.html.erb view code @ present:

<div id="game-genres-form">   <%= fields_for(@game.game_genres.build) |f| %>     <div><%= hidden_field_tag :game_id, @game.id %></div>     <div class="form-group">       <%= f.label :genre_id, "add genre" %>       <div class="input-group">         <%= f.collection_select :genre_id, genre.all, :id, :name,                                         {}, {:class=>'form-control'} %>         <span class="input-group-btn">           <%= f.submit "add", class: "btn btn-default" %>         </span>     </div>   <% end %> </div> 

this not work, because fields_for(@game.game_genres.build) incorrect. in fact, @ present when click 'add' submits new-game form , creates game record doesn't add genre.

i think need know is, use instead of fields_for(@game.game_genres.build) pass submitted genre new array? , how can set up in games_controller.rb?

i realise <div><%= hidden_field_tag :game_id, @game.id %></div> won't necessary (since game_id doesn't exist until new game record has been saved).

i hope i'm making sense, help.


these current associations, missing accepts_nested_attributes_for. i'm not worries @ moment - want know right type of form use, , how make add each genre hash/array.

class game < activerecord::base   belongs_to :user    has_many :game_genres,  foreign_key:  :game_id,                           dependent: :destroy    has_many :genres, through: :game_genres  class gamegenre < activerecord::base    belongs_to :game   belongs_to :genre  class genre < activerecord::base   belongs_to :user    has_many :game_genres,  foreign_key:  :genre_id,                           dependent: :destroy    has_many :games, through: :game_genres 

may missing in game model

accepts_nested_attributes_for :game_genres ,allow_destroy: true 

or can try save genres in view

<%= collection_select(:category, :ids, category.all, :id, :category, { :selected => @categories.map{|m| m.id}}, {:multiple=>true}) %> 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -