简体   繁体   中英

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.

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.

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