Nested Attributes Not Displayed 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

Type (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 is the location field (city) not displayed on the form? I do not get any errors. What am I missing?

+5
source share
1 answer

Good. I’m not sure if you want to choose an existing place to connect with fame or if you want to create a new place for each game.

Assuming this is the first scenario:

Change the relationship in the Game model so that the 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 the location_id field to your game model using migration.

Then, instead of the nested form, you simply change the "Location" field on the game model itself.

, , :

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

game_id , .

, :

def new
 @game = Game.new
 @location = @game.build_location 
end
+5

All Articles