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