如何设计与同一模型具有两个独立且可选关系的模型?
我在设计 User
模型并为其制作合适的表单时遇到了问题。我只是想确保自己做错了:) 所以它是这样的:
用户
有两个地址
:
- 一个用于识别和计费的强制
地址
, - 一个可选的运输
地址< /code> 他可以填写或留空
我尝试这样:
class User < ActiveRecord::Base
has_one :address
has_one :shipping_address, :class_name => 'Address', :foreign_key => 'shipping_address_id'
accepts_nested_attributes_for :address
accepts_nested_attributes_for :shipping_address
#validations for user
end
然后:
class Address < ActiveRecord::Base
#validations for address
end
然后我使用 form_for
和嵌套 fields_for
为 User
制作一个表单代码>.像这样:
= form_for @user, :url => '...' do |a|
= f.error_messages
...
= fields_for :address, @user.build_address do |a|
...
但是,尽管 f.error_messages
会为所有模型生成错误,但 Address
的字段在错误时不会突出显示。
另外,当用户选择不填写第二个地址时,我在禁用第二个地址的验证方面遇到问题。
而且我怀疑我的方法是否正确。我的意思是这个装置的 has_one
关系和整体设计。
那么问题来了:
我做错了吗?如果你处在我的位置,你会怎么做?
I've got a problem with designing my User
model and making a decent form for it. I just want to ensure myself that I'm doing it wrong :)
So it goes like this:
User
has got two Address
es:
- a mandatory
Address
for identification and billing, - an optional shipping
Address
that he could fill in or leave blank
I tried like this:
class User < ActiveRecord::Base
has_one :address
has_one :shipping_address, :class_name => 'Address', :foreign_key => 'shipping_address_id'
accepts_nested_attributes_for :address
accepts_nested_attributes_for :shipping_address
#validations for user
end
and:
class Address < ActiveRecord::Base
#validations for address
end
And then I make a form for User
using form_for
and nested fields_for
. Like this:
= form_for @user, :url => '...' do |a|
= f.error_messages
...
= fields_for :address, @user.build_address do |a|
...
But then, despite that f.error_messages
generates errors for all models, fields for Address
es don't highlight when wrong.
Also I have problems with disabling validation of the second address when the user chose not to fill it in.
And I have doubts that my approach is correct. I mean the has_one
relation and overall design of this contraption.
So the question:
Am I doing it wrong? How would You do that in my place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的表单中的问题在于,每次呈现视图时它都会构建一个新地址,从而丢失所有验证错误。
在您的控制器中,在
new
操作中,您应该执行类似的操作,并在视图中写入:
希望这会有所帮助。
What is wrong in your form is that it will build a new address every time the view is rendered, thus losing all validation errors.
In your controller, in the
new
action you should do something likeand in your view write:
Hope this helps.