ruby on rails - How to populate a dropdown [rails4] -
so, have app lets users upload , comment on songs. however, i'd add genres category. when users upload songs they'll able choose genre of song. when add search.
for quick overview of code see: www.github.com/apane/leap
i'm guessing i'd add genres table db , associate songs e.g:
genre belongs_to song, song has_many genres.
but after i'm stumped. how populate genres dropdown?
rails g model genre name rails g model genre_song genre:belongs_to song:belongs_to rake db:migrate
models/genre.rb
has_many :genre_songs has_many :songs, through: :genre_song
models/song.rb
has_many :genre_songs has_many :genres, through: :genre_song def self.tagged_with(name) genre.find_by_name!(name).songs end def tag_list genres.map(&:name).join(", ") end def tag_list=(names) self.genres = names.split(",").map |n| genre.where(name: n.strip).first_or_create! end end
songs/index.html.erb
genres: <%= raw song.genres.map(&:name).map { |t| link_to t, genre_path(t) }.join(', ') %>
songs/_form.html.erb
<div class="field"> <%= f.label :tag_list, "genres (separated commas)" %><br /> <%= f.text_field :tag_list %> </div>
songs_controller.rb
add tag_list
permited params
Comments
Post a Comment