has_one关系的嵌套表单属性

时间:2013-03-04 23:49:35

标签: ruby-on-rails-3 ruby-on-rails-3.2

我已经搜索了SO和互联网很长一段时间了,但还是没能弄明白这一点。我有一个模型项目,它总是有一个TimerSetting。没有涉及的联接表。

在新项目表单中,我尝试使用嵌套属性来创建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块中的字段。

非常感谢任何建议/帮助!

1 个答案:

答案 0 :(得分:0)

您的TimerSetting需要project_id。你的项目不需要使用timer_settings_id,因为rails会通过你的TimerSetting模型的project_id找到它。

相关问题