Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested attributes not showing up in simple form

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?

like image 599
Hommer Smith Avatar asked May 10 '12 06:05

Hommer Smith


1 Answers

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
like image 82
julesie Avatar answered Oct 12 '22 10:10

julesie