在不存在的方法上使用 Rails 表单助手
通常,在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定你的用户模型“脏”是什么意思,但你可以使用 attr_accessor 方法。这将允许您为模型创建一个可用于验证的属性:
要仅在特定时间运行验证,您可以使用
: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:
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.Yehuda Katz 有一个很好的解释< /a> 如何使用
ActiveModel
使任意类与 Rails 的表单助手兼容。不过,这只适用于 Rails 3。如果您不生活在最前沿,请观看Railscasts 第 193 集“无桌模型”,它描述了如何创建一个像
ActiveRecord::Base
一样足够嘎嘎的类,它可以与form_for
一起使用。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 withform_for
.