2012-08-03 67 views

回答

0

没有直接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

+0

这看起来很合理,谢谢! – 2012-08-03 20:04:37