Given the following:
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
  def new
    @game = Game.new
  end
<%= 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?
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With