创建同时具有 own_to 和 validates_presence_of 验证的对象的正确方法是什么?
我想创建一个对象,它既验证父对象的存在,又验证父对象的有效性。但是我想独立于父对象创建它,但我不知道如何这样做。
这是我的代码:
class User
has_many :questions
end
class Question
belongs_to :user
validates_presence_of :user
validates_associated :user
end
我知道我可以这样做:
u = User.create
q = u.questions.create
但是我需要这样做
u = User.create
q = Question.create(:user_id => u.id)
q.valid?
=> false
q.errors?
=> <OrderedHash {:user=>["can't be blank"]}>
处理这个问题的正确方法是什么?
应该我使用
class User
...
before(:save) do
self.user = User.find(self.user_id)
end
end
这看起来不必要的混乱 - 有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您也许应该在问题模型中使用
validates_the_presence_of :user_id
而不是validates_presence_of :user
。我希望它会有所帮助。
You should maybe use
validates_the_presence_of :user_id
in the Question Model instead ofvalidates_presence_of :user
.I hope it would help.
您想通过表单创建对象吗?如果您是,那么我建议使用 build 方法并接受_nested_attributes - 这将允许您同时创建父对象和子对象。我通常参考 Ryan 的帖子 当想要这样做时。
Are you wanting to create the object through a form? If you are then I would suggest using the build method and accepts_nested_attributes - this will allow you to create both the parent object and a child object at the same time. I usually reference Ryan's post when wanting to do this.