Ruby on rails 防止直接创建Rails3模型(仅允许从其他模型中创建)
我想确认一下Ruby on rails 防止直接创建Rails3模型(仅允许从其他模型中创建),ruby-on-rails,ruby,model,Ruby On Rails,Ruby,Model,我想确认一下 MyModel.new # ...raises an error... 那 MyOtherModel::create_my_model # ...only this should work! 做这件事的好方法是什么 谢谢。没什么直接的。不过,下面的方法应该可以奏效 class MyModel < ActiveRecord::Base .. belongs_to :my_other_model def initialize( need_this_argument
MyModel.new # ...raises an error...
那
MyOtherModel::create_my_model # ...only this should work!
做这件事的好方法是什么
谢谢。没什么直接的。不过,下面的方法应该可以奏效
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
classmymodel
MyModel.new#=>运行时错误a=MyOtherModel.new
b=a.创建我的模型
..#在这里做你的事
b、 保存
a、 保存