在不存在的方法上使用 Rails 表单助手

发布于 2024-08-22 06:58:46 字数 164 浏览 12 评论 0原文

通常,在 Rails 中使用表单助手时,每个字段都直接与相应对象上的方法相关联。

但是,我有一个表单(用户注册),需要包含不属于用户模型本身的字段(例如,卡详细信息)但需要显示。

如何构建表单,以便获得必要的字段,并根据需要验证它们(以便它适合我所有其他验证)而不弄脏我的用户模型?

Normally, when using form helpers in Rails, each field directly correlates to a method on the appropriate object.

However, I have a form (user signup) that needs to include fields that are not part of the user model itself (for instance, card details) but need to appear.

How can I build the form so that I can get the necessary fields, and validate them as I need to (so that it fits with all my other validations) without dirty-ing my user model?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

烧了回忆取暖 2024-08-29 06:58:46

我不确定你的用户模型“脏”是什么意思,但你可以使用 attr_accessor 方法。这将允许您为模型创建一个可用于验证的属性:

class Widget < ActiveRecord::Base
  attr_accessor :confirmation_email
  validates_length_of :confirmation_email, :within => 1..10
end

要仅在特定时间运行验证,您可以使用 :if 条件:

validates_length_of :confirmation_email, :内 => 1..10,:如果=> Proc.new { |小部件| widget.creation_step > > 2 }

您还可以使用类方法,例如: :if => :付款_完成。有了这些你应该能够实现你想要的功能。据我所知,没有更简洁的方法。

I'm not sure what you mean by "dirty-ing" your user model, but you can do this using the attr_accessor method. This will allow you to create an attribute for the model that can be used for validations:

class Widget < ActiveRecord::Base
  attr_accessor :confirmation_email
  validates_length_of :confirmation_email, :within => 1..10
end

To only run the validation at certain times, you could use an :if condition:

validates_length_of :confirmation_email, :within => 1..10, :if => Proc.new { |widget| widget.creation_step > 2 }

You can also use a class method, like: :if => :payment_complete. With these you should be able to achieve the functionality you want. As far as I know there isn't any more concise way.

苄①跕圉湢 2024-08-29 06:58:46

Yehuda Katz has a great explaination of how you can use ActiveModel to make an arbitrary class compatible with Rails' form helpers. That only works if you're on Rails 3, though.

If you're not living on the bleeding edge, watch Railscasts episode 193, "Tableless Model", which describes how you can create a class that quacks enough like ActiveRecord::Base that it works with form_for.

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