Rails3嵌套属性在保存操作中使用父值
我在rails3应用程序中有一个简单的嵌套表单。 我正在尝试解决如何在保存时将父模型中的值保存到子模型中。
class Radcheck < ActiveRecord::Base set_table_name 'radcheck' attr_accessible :attribute_name, :username, :value, :op belongs_to :raduser end class Raduser :destroy accepts_nested_attributes_for :radcheck end
我的表格:
我想要做的是在保存时将Raduser.username值保存到radcheck表中。 对于每条记录。
我已经尝试在控制器中放置一些东西,但这对我们来说并不适用。
– 更新 –
在我的radcheck控制器中,我试过这个(作为测试),但值不能保存。
def create @radcheck = Radcheck.new(params[:radcheck]) @radcheck.username = '123' respond_to do |format| if @radcheck.save format.html { redirect_to @radcheck, notice: 'Radcheck was successfully created.' } format.json { render json: @radcheck, status: :created, radcheck: @radcheck } else format.html { render action: "new" } format.json { render json: @radcheck.errors, status: :unprocessable_entity } end end end
也试过radusers,但这给了错误。
您发布的控制器代码看起来像是Radcheck控制器,对吗? 如果是这样,您发布的表单将使用RaduserController
类的create
操作,而不是RaduserController
的create
操作。 这可以解释为什么你没有在radcheck行中看到用户名’123’。
如果父元素和子before_save
之间的用户名字段相同,则将这两者同步的常用方法是使用观察者或before_save
回调。 我将概述下面的before_save
方法:
class Radcheck < ActiveRecord::Base set_table_name 'radcheck' attr_accessible :attribute_name, :username, :value, :op belongs_to :raduser before_save :sync_usernames private def sync_usernames self.username = self.raduser.username end end
我用Rails 3.1对它进行了测试,它可以工作; 但是,我知道在以前版本的Rails中访问子模型中的父模型时遇到了问题。 在这些情况下,我必须将before_save
操作放在父模型上,并让它迭代每个子节点,以这种方式设置适当的属性。