【发布时间】:2013-03-27 16:44:03
【问题描述】:
关于我面临的一个简单问题的快速问题(我想以此作为一种方式来更深入地了解有关关联和 Rails 的一些事情)。如下:
两个关联的模型是
class Employee < ActiveRecord::Base
attr_accessible :name
attr_accessible :age
belongs_to :role
attr_accessible :role_id
end
class Role < ActiveRecord::Base
attr_accessible :title
attr_accessible :salary
has_many :employees
end
这样每个新员工都有固定的工资,根据他的角色(大多数时候都是这种情况)。但是,如果我想为特定员工设置不同的工资怎么办?
到目前为止,我使用simple_form 编写了以下内容:
<%= f.input :name, label: 'Employee Name', :required => true %>
<%= f.association :role, as: :radio_buttons, :required => true %>
<%= f.input :salary, label: 'Employee Salary', :input_html => { :value => 0 }, :required => true %>
这当然会给我一个can't mass assign protected attributes: salary 错误。
为了解决这个问题,我将attr_accessible :salary 添加到Employee 模型中,但这只是将错误更改为unknown attribute: salary。
据我了解,我必须首先在新员工中更改某些内容,然后在员工模型和控制器中进行更改,以便它接受薪水值并知道如何处理它,对吗?
我也看到使用了accepts_nested_attributes_for,但我不完全确定它应该放在关联的哪一边——因为我也不完全确定关联的架构是最好的。
【问题讨论】:
标签: ruby-on-rails ruby associations nested-attributes simple-form