I’m currently reading Rails 3 In Action. There is code that I was wondering if someone could explain to me. I’m having a hard time understanding it:
scope :readable_by, lambda { |user| joins(:permissions).where(permissions: { action: "view", user_id: user.id })}
thanks,
mike
It’s called a Rails scope. It essentially creates a class method called
.readable_by(user)that does a SQL join on the permissions table and returns records where theactioncolumn value is “view” and theuser_idcolumn value equalsuser.id.It could be used like so (assuming it’s defined in the
Commentsmodel):A simple scope that does nothing is this:
A scope that accepts a parameter is this:
And then the above scope uses some ActiveRecord finder methods, specifically
joinsandwhere.