Rails 新手在这里。在我的应用程序中,我试图创建一个游戏数据库,每个游戏都有多个 MameControls 作为嵌套属性。用于输入 MameControls 的字段显示在 New 视图中,但不在 Edit 中,结果不会在 Show 中呈现,如果我 validate_presence_of :mameControls 它不会保存表单,说明“Mame 控件不能为空”。在 rails 控制台中, Game.first(或 last,或任何其他记录).mame_controls 仅返回[]
. 所以据我所知,嵌套属性没有被保存,即使我很确定我已经设置了类似于 Railscast #196 中显示的所有内容。这是游戏类:
class Game < ActiveRecord::Base
has_many :mame_controls, :dependent => :destroy
attr_accessible :name, :year, :company, :designer, :genre,
:sb_info, :wiki_link, :arcade_history_link, :arcade_museum_link,
:caesar_link, :wildcard_link, :mame_controls
accepts_nested_attributes_for :mame_controls, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
validates_presence_of :name, :year, :company, :genre, :sb_info, :mame_controls
end
mame_control.rb:
class MameControl < ActiveRecord::Base
belongs_to :game
attr_accessible :name, :game_action
end
输入或编辑 MameControls 的表单代码是这样的。
在 _form.html.erb 中:
<% f.fields_for :mame_controls do |builder| %>
<%= render "control_fields", :f => builder %>
<% end %>
_control_fields.html.erb:
<div class="field">
<p>
<%= f.label :name, "Mame Control Name" %><br />
<%= f.text_field :name %><br />
<%= f.label :game_action, "Game Action" %><br />
<%= f.text_field :game_action %>
</p>
</div>
在 games_controller.rb 中:
def new
@game = Game.new
5.times do
mame_control = @game.mame_controls.build
end
end
def create
@game = Game.new(params[:game])
end