2010-01-22 58 views
1

我有一个模型,当它实例化一个对象时,还会使用相同的用户ID创建另一个对象。在rails中绕过attr_accessible/protected

class Foo > ActiveRecord::Base 

after_create: create_bar 

private 

def create_bar 
    Bar.create(:user_id => user_id #and other attributes) 
end 

end 

在Bar.rb中,我有attr_protected以保护它免受黑客攻击。

class Bar > ActiveRecord::Base 
    attr_protected :user_id, :created_at, :updated_at 
end 

目前的情况是,我似乎无法不创建一个新的酒吧对象要么禁用attr_protected或具有Bar对象的user_id一片空白......

我怎样才能让酒吧对象接受:来自foo的user_id属性不会失去对attr_protected的保护?

回答

2

尝试做:

def create_bar 
    bar = Bar.build(... other params ...) 
    bar.user_id = user_id 
    bar.save! 
end 
+1

This Works!谢谢jonnii。除了在我的情况下,我做了bar = user.bar.build(...参数) – 2010-01-22 21:09:33

2

attr_protected过滤在attributes=方法至极的属性被称为new。你可以解决你的问题:

def create_bar 
    returning Bar.new(other attributes) do |bar| 
    bar.user_id = user_id 
    bar.save! 
    end 
end 
+0

啊!我明白,只要你摆脱新困境,它就会起作用。这就是为什么其他答案也适用于我。 – 2010-01-22 21:11:48

+0

此版本返回对象,如您的示例中所示,不是true/false。 – gaspard 2010-01-23 06:55:27