简体   繁体   中英

In Rails, how can I only use validates_inclusion_of when the model is created, NOT every time it is updated?

I have an object, called Account, and there is a campaign source associated with every account. Currently, if the Account is updated, and there is no campaign source, you have to update the campaign source (the possible values of which are in a selectlist).

I know that validates_presence_of has an :on option, which allows you to specify :create, :update or :save, but validates_inclusion_of does not have this option, unfortunately. How can I get around this? Thanks.

Here is my code:

class Account < ActiveRecord::Base
  validates_inclusion_of :campaign_source, :in => CampaignSource.list, :message => "^Please let us know how you heard about us"

Try

validates :campaign_source, :inclusion => { :in => CampaignSource.list },
                            :message => "^Please let us know how you heard about us",
                            :on => :create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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