简体   繁体   English

使用Rails在不存在的方法上形成帮助器

[英]Using Rails form helpers on non-existent methods

Normally, when using form helpers in Rails, each field directly correlates to a method on the appropriate object. 通常,在Rails中使用表单助手时,每个字段都直接与相应对象上的方法相关联。

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

I'm not sure what you mean by "dirty-ing" your user model, but you can do this using the attr_accessor method . 我不确定你的用户模型“脏”是什么意思,但你可以使用attr_accessor方法来做到这一点。 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: 要仅在特定时间运行验证,您可以使用:if条件:

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 . 您还可以使用类方法,例如: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 has a great explaination of how you can use ActiveModel to make an arbitrary class compatible with Rails' form helpers. Yehuda Katz 很好地解释了如何使用ActiveModel使任意类与Rails的表单助手兼容。 That only works if you're on Rails 3, though. 但这只适用于你在Rails 3上的情况。

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 . 如果你不是生活在最前沿,请观看Railscasts第193集“无表模型” ,它描述了如何创建一个类似于ActiveRecord::Base ,它与form_for

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM