views:

125

answers:

3

If I have a Model like the following example

class Person < ActiveRecord::Base 
   has_many :moods
end 

 class Mood <ActiveRecord::Base
 end

how do I change the new.html.erb allow me to choose a mood when entering a new Person? Do I need to add the foreign keys to mysql manually?

+4  A: 

If you want a select menu, you're looking for the collection_select helper.

Check out Formtastic, it can generate a nice select menu for your has_many for you.

Jeff Paquette
+1  A: 

Rails migrations does not create foreign keys automatically. Either the constraint has to added during migrations with a command similar to the following:

execute "alter table moods add constraint fk_moods_persons foreign key (person_id) references persons(id)"

There are plugins which does this job automatically and makes the job simpler. Few of the popular ones are:

  1. Foreigner
  2. Redhill On Rails Core [www.railslodge.com/plugins/389-redhill-on-rails-core]

And for displaying in views, collection_select helper can be used.

I guess habtm will be a better association (if more than one person can have the same mood.) Or has_many :through is even better.

Selva
+1  A: 

From the few details you gave, it is a little hard to guess, what you are trying to do. But I'll try anyway:

When you want a person to have exactly one mood at a time, I would model it like this:

class Person < ActiveRecord::Base 
  belongs_to :mood
end 

class Mood < ActiveRecord::Base
  has_many :people
end

The migration to create the people table in the database should then include the following statement to create a foreign key:

def self.up
  create_table :people do |t|
    ...
    t.references :mood
    ...
  end
end

If this is what you want, you can use the collection_select command as flyfishr64 pointed out.

Inside the form_for tag in new.html.erb you would write something like this:

<% form_for @person do |f| %>
...
<%= f.collection_select :mood_id, Mood.all, :id, :mood_name, :include_blank => "--- Choose your mood ---" %>
...
<% end %>

Hope that helps!

However, when you really want your person to have multiple moods simultaneously, this would be a little more complicated, and I probably would suggest to use the has_and_belongs_to_many association in both models.

If that's the case, I would recommend watching this Railscast episode: HABTM Checkboxes. (Sorry, you have to look for the link yourself, as I am not allowed to post more than one line. Go to railscast.com and look for episode 17.)

Daniel Pietzsch