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 do |n|
Genre.where(name: n.strip).first_or_create!
end
end
曲/index.html.erb
Genres: <%= raw song.genres.map(&:name).map { |t| link_to t, genre_path(t) }.join(', ') %>
曲/_form.html.erb
<div class="field">
<%= f.label :tag_list, "Genres (separated by commas)" %><br />
<%= f.text_field :tag_list %>
</div>
song_controller.rb
tag_list
許可されたパラメータに追加