Nested attributes not showing up in simple form

拥有回忆 提交于 2019-12-23 10:09:02

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/10528582/nested-attributes-not-showing-up-in-simple-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!