Rails newb在這裏。在我的應用程序中,我試圖創建一個遊戲數據庫,每個遊戲都有多個MameControls作爲嵌套屬性。用於輸入MameControls的字段顯示在New視圖中,但不在Edit中,結果不顯示在Show中,並且如果我validate_presence_of:mameControls它不會保存表單,說明「Mame控件不能爲空」。在Rails控制檯中,Game.first(或最後或其他任何記錄).mame_controls僅返回[]
。所以據我所知,嵌套屬性並沒有被保存,儘管我很確定我已經把所有東西都設置成類似於Railscast#196中顯示的內容。下面是遊戲類:無法在Rails中保存嵌套屬性
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
謝謝,但我恐怕添加:mame_controls_attributes attr_accessible沒有任何區別。別擔心,這些控件不在演出中。我的意思是簡單地說數據不會顯示在那裏(作爲靜態信息)。對不起,我不清楚,我已經修復了原來的帖子。 – user541269 2010-12-14 14:26:50