2013-03-04 81 views
0

我已經搜索了SO和互聯網很長一段時間,但一直未能弄清楚。我有一個模型項目,總是有一個TimerSetting。不涉及任何連接表。has_one關係的嵌套表單屬性

在新的項目形式中,我試圖使用嵌套屬性來創建一個TimerSetting記錄。無法弄清楚這一部分。

相關代碼的機型:

項目型號:

class Project < ActiveRecord::Base 
    attr_accessible :timer_setting_id 

    has_one :timer_setting 
    accepts_nested_attributes_for :timer_setting 
end 

TimerSetting型號:

class TimerSetting < ActiveRecord::Base 
    attr_accessible :rounding_method, :round_to 

    belongs_to :project 
end 

在項目負責人:

def new 
    @project.new 
    @project.build_timer_setting 
end 

在視圖:

<%= form_for @project, {remote: true, format: 'json'} do |f| %> 
    ... other stuff ... 
    <%= f.fields_for :timer_setting do |ts| %> 
     Rounding Method <%= ts.check_box :rounding_method %> 
     Round To <%= ts.text_field :round_to %> 
    <% end %> 
<% end %> 

當我調用路徑渲染窗體(projects/new)時,rails會說:unknown attribute: project_id。如果我在項目控制器註釋掉該行

#@project.build_timer_setting 

將呈現形式,但在f.fields_for :timer_setting塊中的字段不輸出。

任何意見/幫助將不勝感激!

回答

0

您的TimerSetting需要一個project_id。您的項目不需要timer_settings_id,因爲rails會通過TimerSetting模型的project_id找到它。