简体   繁体   中英

Rails 3: Having trouble with nested forms and has_many :through

Here's my model set up.

Band Model

has_many :bands_genres
has_many :genres, :through => :bands_genres

Genre Model

has_many :bands_genres
has_many :bands, :through => :bands_genres

BandsGenre Model

belongs_to :band
belongs_to :genre

I have a form where you can add a new band and then select a genre from a dropdown field that pulls from the pre-set genres in the genre model.

So what I ultimately need to do is set up a form so that when a band adds their band and select a genre, it creates the correct join in the bands_genre model.

Not sure where to start with setting up the form, controllers and models for this.

I'm running Rails 3.0.3

There are quite a few text/video casts covering this, since its a popular use case. I would encourage you to look at: http://railscasts.com/episodes/73-complex-forms-part-1 or its equivalent asciicast (which is a text based cast of the video).

Further I would recommend you use formtastic. Associations are managed automatically so it makes form building trivial and keeps your code tidy. And yes there are casts for that too. http://railscasts.com/episodes/184-formtastic-part-1

Edit:

Band Model

has_many :genres, :as => :band_genres                                        

Genre Model

has_many :bands, :as => :band_genres

Your genre table has a band_id , and your band table has a genre_id .

bands_controller

def new
   @genres = Genre.all
   @post = Post.new
end

posts/new.html.haml (This part I'm a little unsure of, but it roughly goes like this)

- form_for @post do |f|
   = f.select :genre_id, @genres, {}
   = f.submit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM