I would like to create an object which both validates the presence of a parent object AND validates the validity of the parent object. However I would like to create it independently of the parent object and I’m not sure how to do so.
This is my code:
class User
has_many :questions
end
class Question
belongs_to :user
validates_presence_of :user
validates_associated :user
end
I know I can do this:
u = User.create
q = u.questions.create
but I need to do this
u = User.create
q = Question.create(:user_id => u.id)
q.valid?
=> false
q.errors?
=> <OrderedHash {:user=>["can't be blank"]}>
What is the correct way to deal with this?
Should I use
class User
...
before(:save) do
self.user = User.find(self.user_id)
end
end
This seems unnecessarily messy – is there a better way?
You should maybe use
validates_the_presence_of :user_idin the Question Model instead ofvalidates_presence_of :user.I hope it would help.