I am using Ruby on Rails 3.2.2 and I would like to know what is a common approach when it must be checked if an user has proper authorizations to \"read\" records present in
It depends on your readable_by_user function. If it is easy to translate into an SQL, than it is the way forward. If it is more complicated than that then you most probably have to do the check manually.
UPDATE: To clarify the point of creating an SQL query for the readable list I present an example. Assume, that a readability of an article to a given user is dependent of the following:
SELECT a.user == ? FROM Articles a WHERE a.id = ?)SELECT a.state == 0 FROM Articles a WHERE a.user = ?)sql:
SELECT max(g.rights) > 64
FROM Groups g
JOIN Groups_users gu on g.id = ug.group_id
WHERE gu.id = ?
sql:
SELECT 1
FROM Articles_users au
WHERE au.article_id = ? AND au.user_id = ?
These can be summarized in the following query:
def articles_for_user(user)
Articles.find_by_sql(["
SELECT a.*
FROM Articles a
LEFT OUTER JOIN Articles_users au on au.article_id = a.id and au.user_id = ?
WHERE a.user_id = ?
OR au.user_id = ?
OR 64 <= (SELECT max(g.rights)
FROM Groups g
JOIN Groups_users gu on g.id = ug.group_id
WHERE gu.id = ?)
", user.id, user.id, user.id, user.id])
end
This is sure a complicated query, but the most efficient solution. The database should do database stuff, if you only use SQL queries and some logic to evaluate your readable_bu_user then you can translate it into one pure SQL query.