5

Given the following:

Models

class Location < ActiveRecord::Base
  has_many :games
end

class Game < ActiveRecord::Base
  validates_presence_of :sport_type

  has_one :location
  accepts_nested_attributes_for :location
end

Controller

  def new
    @game = Game.new
  end

View (form)

<%= simple_form_for @game do |f| %>
  <%= f.input :sport_type %>
  <%= f.input :description %>
  <%= f.simple_fields_for :location do |location_form| %>
    <%= location_form.input :city %>
  <% end %>
  <%= f.button :submit %>
<% end %>

Why the locations field (city) are not showing up in the form? I am not getting any error. What am I missing?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

5

Ok I'm not sure if you are looking to pick an existing location to associate with the fame or if you are wishing to create a new location for each game.

Assuming it is the first scenario:

Change the association in the Game model so that a game belongs to a location.

class Game < ActiveRecord::Base
  validates_presence_of :sport_type

  belongs_to :location
  accepts_nested_attributes_for :location
end

You may need to add a location_id field to your Game model via a migration.

Then instead of a nested form you are just going to be changing the Location field on the Game model itself.

If it is the second scenario and you wish to build a new location for each game then you will need to change your models as follows:

class Location < ActiveRecord::Base
  belongs_to :game
end

class Game < ActiveRecord::Base
   validates_presence_of :sport_type

  has_one :location
  accepts_nested_attributes_for :location
end

You will need to add a game_id field to the location model if you do not already have one.

Then in your controller you will need to build a location in order to get the nested form fields to show:

def new
 @game = Game.new
 @location = @game.build_location 
end
julesie
  • 104
  • 4
  • If I do that, I get: unknown attribute: game_id – Hommer Smith May 10 '12 at 08:46
  • It works, but why would I need to use belongs_to instead of has_one?? – Hommer Smith May 10 '12 at 09:20
  • 2
    Saying a game HAS_ONE location means you expect the location table to reference a game_id. However that is at odds with your other association which says a location HAS_MANY games, which would expect the game table to hold a location_id. It looks to me that a game BELONGS_TO location and that it should be the table to hold the location_id\ – julesie May 10 '12 at 09:25