Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 旁路属性可在轨道中访问/保护_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 旁路属性可在轨道中访问/保护

Ruby on rails 旁路属性可在轨道中访问/保护,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我有一个模型,当它实例化一个对象时,也会创建另一个具有相同用户id的对象 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_进行了保护,以防黑客攻击 class Bar > ActiveRecord::B

我有一个模型,当它实例化一个对象时,也会创建另一个具有相同用户id的对象

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_进行了保护,以防黑客攻击

class Bar > ActiveRecord::Base
  attr_protected :user_id, :created_at, :updated_at
end
现在看来,如果不禁用attr\u protected或者让Bar对象的用户id变为空白,我就无法创建新的Bar对象

如何让bar对象接受来自foo的:user\u id属性,而不失去来自attr\u protected的保护?

尝试执行以下操作:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end
试着做:

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

attr\u protected
过滤
attributes=
方法中的属性,该方法在
new
中调用。您可以通过以下方式解决您的问题:

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

attr\u protected
过滤
attributes=
方法中的属性,该方法在
new
中调用。您可以通过以下方式解决您的问题:

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

调用
new
create
find_或_create_by
(以及最终调用
new
的任何其他人)时,您可以传递一个附加选项,
无保护:true


当调用
新建
创建
、或
查找或创建
(以及最终调用
新建
的任何其他人)时,您可以传递一个附加选项,
而无需保护:true


这很有效!谢谢你,乔尼。除了在我的例子中,我做了bar=user.bar.build(…参数)这是可行的!谢谢你,乔尼。除了在我的例子中我做了bar=user.bar.build(…参数)啊!我明白了,只要你离开纽约,它就行。这就是为什么另一个答案也适用于我。这个版本返回的对象与您的示例中的一样,不是真/假。啊!我明白了,只要你离开纽约,它就行。这就是为什么另一个答案也适用于我。这个版本返回的对象与您的示例中的一样,不是真/假。