0
我想确保防止Rails3中模型(只希望允许创建从另一个模型中)
MyModel.new # ...raises an error...
和
MyOtherModel::create_my_model # ...only this should work!
什么是好办法做这个?
谢谢。
我想确保防止Rails3中模型(只希望允许创建从另一个模型中)
MyModel.new # ...raises an error...
和
MyOtherModel::create_my_model # ...only this should work!
什么是好办法做这个?
谢谢。
没有直接AFAIK。以下应该工作。
class MyModel < ActiveRecord::Base
..
belongs_to :my_other_model
def initialize(need_this_argument = nil)
raise if need_this_argument.nil?
super() # It is important to put the() here.
end
end
class MyOtherModel < ActiveRecord::Base
...
has_one :my_model
accepts_nested_attributes_for :my_model
def create_my_model(arguments)
MyModel.new(true) # Pass a non nil argument
end
end
MyModel.new#=> RuntimeError
A = MyOtherModel.new
B = a.create_my_model
..#做你的东西在这里
b.save
a.save
这看起来很合理,谢谢! – 2012-08-03 20:04:37