如何设计与同一模型具有两个独立且可选关系的模型?

发布于 2024-12-07 08:33:18 字数 1150 浏览 3 评论 0原文

我在设计 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_forUser 制作一个表单代码>.像这样:

= 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 Addresses:

  • 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 Addresses 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮坠入山谷 2024-12-14 08:33:18

您的表单中的问题在于,每次呈现视图时它都会构建一个新地址,从而丢失所有验证错误。

在您的控制器中,在 new 操作中,您应该执行类似的操作

@user.build_address

,并在视图中写入:

= fields_for :address, @user.address do |a|

希望这会有所帮助。

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 like

@user.build_address

and in your view write:

= fields_for :address, @user.address do |a|

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文