byCoder
byCoder

Reputation: 9184

Rails validate only in admin namespace

In my rails app i have two user-logic:

user, and admin

for example my routing for line_item is such:

namespace :admin do
  resources :line_items, :only => [:edit, :update, :destroy]
end
resources :line_items, :only => [:new, :create, :update, :edit, :destroy]

but in admin part i must to do vailation for my line_item model:

  validates :notes, :presence => {:message =>  I18n.t(:notes_not_chosen)}
  validates :quantity, :presence => {:message =>  I18n.t(:quantity_not_chosen)}
  validates :price, :presence => {:message =>  I18n.t(:price_not_chosen)}
  validates :description, :presence => {:message =>  I18n.t(:description_not_chosen)}

But only in admin controller! How to do that i have validations only in admin line_item controller, but didn't have in user part?

Upvotes: 1

Views: 1426

Answers (1)

Andre Bernardes
Andre Bernardes

Reputation: 1623

I don't think you can do validations based on which controller your request came through. What you can do is add a user attribute to your model and set it in the controller. Then you can base your validation on the user attribute. Like so:

Controller:

def create
  @line_item = LineItem.new(params[:line_item])
  @line_item.user = current_user
  if @line_item.save 
  # ... standard rails stuff
end

Model:

class LineItem < ActiveRecord::Base
  attr_accessor :user

  validates :notes, :presence => true, :if => Proc.new { user.admin? }
end

Upvotes: 2

Related Questions