开发者

rails custom validation on action

开发者 https://www.devze.com 2023-02-11 16:23 出处:网络
I would like to know if there\'s a way to use rails validations on a custom action. For example I would like do something like this:

I would like to know if there's a way to use rails validations on a custom action.

For example I would like do something like this:

validates_presence_of :description, :on => :publish, :message => "can't be blank"

I do basic validations create and save, but there are a great many things I don't want to require up front. Ie, they should be able to save a barebones record without validating all the fields, however I have a custom "publish" action and state in my controller and model that when used should validate to make sure the record is 100%

The above example didn't work, any ideas?

UPDATE:

My state machine looks like this:

  include ActiveRecord::Transitions
  state_machine do 
    state :draft
    state :active
    state :offline

    event :publish do
      transitions :to => :active, :from => :draft, :on_transition => :do_submit_to_user, :guard => :validates_a_lot?
    end

  end

I foun开发者_运维技巧d that I can add guards, but still I'd like to be able to use rails validations instead of doing it all on a custom method.


That looks more like business logic rather than model validation to me. I was in a project a few years ago in which we had to publish articles, and lots of the business rules were enforced just at that moment.

I would suggest you to do something like Model.publish() and that method should enforce all the business rules in order for the item to be published.

One option is to run a custom validation method, but you might need to add some fields to your model. Here's an example - I'll assume that you Model is called article

Class Article < ActiveRecord::Base
  validate :ready_to_publish

  def publish
    self.published = true
    //and anything else you need to do in order to mark an article as published
  end

  private
  def ready_to_publish
    if( published? ) 
      //checks that all fields are set 
      errors.add(:description, "enter a description") if self.description.blank?
    end
  end
end

In this example, the client code should call an_article.publish and when article.save is invoked it will do the rest automatically. The other big benefit of this approach is that your model will always be consistent, rather than depending on which action was invoked.


If your 'publish' action sets some kind of status field to 'published' then you could do:

validates_presence_of :description, :if => Proc.new { |a| a.state == 'published' }

or, if each state has its own method

validates_presence_of :description, :if => Proc.new { |a| a.published? }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号