Praveen George
Praveen George

Reputation: 9715

Conditional Statements In Ruby on Rails Model File

Is it possible for us to write conditional statements in our Rails model file for example in my case if I want to implement some validations based on if a user is singned_in or not in my Customer.rb file.

if user_signed_in?  // if signed_in is true
     //my validation code here

then some special validations and

else !user_signed_in? // if signed_in is false
     //my validation code here

Upvotes: 2

Views: 1307

Answers (2)

sugaryourcoffee
sugaryourcoffee

Reputation: 879

Something like this?

validates :my_attribute, presence: :true, if: :user_signed_in? validates :my_attribute, presence: :false, unless: :user_signed_in?

Upvotes: 0

Richard Peck
Richard Peck

Reputation: 76774

current_user, user_signed_in? etc are not available in the model.

Rails 3 devise, current_user is not accessible in a Model ?

In short, your user-centric conditions should be in the controller, the model is to pull & manipulate data only...

enter image description here

I post this image all the time; it shows how a standard MVC framework looks. Rails is an MVC framework... shows you how the model and other elements work together to get it working properly.

As you can see, the controller acts like the "hub" which glues it all together. In order to keep your application structured properly, you'll ideally want to put your mid-level logic in your controller, data-level logic into your model, and superficial logic into your view.

EG:

#Model
class Products
   belongs_to :user
end

#controller
def index
   @products = user_signed_in? ? current_user.products : Product.all
end

#view
<% @products.each do |product| %>
   <%= product.name if product.name %>
<% end %>

The answer you need is to specify the validation logic you require, allowing you to apply the required data in the controller/model


If you wanted to use user validation in the model, you'd have to use conditions at the controller level and pass the results to the model:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def create
      @user = User.new user_params
      @user.online = user_signed_in?
   end

   private

   def user_params
      params.require(:user).permit(:x, :y, :z)
   end
end

#app/models/user.rb
class User < ActiveRecord::Base
   validates :online, presence: true
end

Upvotes: 3

Related Questions