zakelfassi
zakelfassi

Reputation: 2966

Calling Rails model from another model

Is it considered a best practice to call a Rails model from another model ? (code below) :

#models/user.rb
def get_pending_requests(user_id)
  Friend.where("friend_id = ? AND approved = ?", user_id, false)
end

I find it a bit awkward to perform RSpec/FactoryGirl tests doing this, as opposed to perform these actions from within a Controller.

Upvotes: 2

Views: 1949

Answers (1)

Sean Hill
Sean Hill

Reputation: 15056

Might I suggest a different approach? Assuming that your models are setup like this:

class Friend < ActiveRecord::Base
  belongs_to :user

  scope :pending, -> { where(approved: false) }
end

class User < ActiveRecord::Base
  has_many :friends

  def pending_requests
    friends.pending
  end
end

So you create a scope called pending on friend. Then you can use that scope on your friends relation. I find this to be a more standard approach.

Upvotes: 5

Related Questions