0

I am using Rails 3, and building an app in which a user can put objects to be rented. For each object, he can decide:

  • the object can be rented by the entire world (potentially) or not (object access is restricted)
  • the object can only be rented by my friends (in the app, via a has_many friends, :through => friendship association)
  • the object can be rented by members of the following groups (then the user selects either all the groups he belongs to, or a subset of these)

My question is how to display the list of objects a current_user can see ? I see two options, and I would like to know which is the best one or if they are equivalent:

1) In the object controller, build the collection of the objects a user can see (@objects = Object.can_see(current_user)) and then pass this to the index view and display the whole list

2) In the controller, collect ALL objects (@objects = Object.all), pass this to the index view, and in the view, for each object, conduct a serie of test to determine if the object should be displayed or not.

4

1 回答 1

1

In the end, it is really up to you to decide based on where you see the project headed. You really have three options though:

  1. Handle the entire query via SQL statements.
  2. Handle some of the initial filtering via SQL statements, then filter the returned data.
  3. Return all of the data via SQL statements, and filter the returned data.

Keep in mind that SQL db's are built for performing fast data access. I would be very surprised if your solution didn't have any initial filtering, unless you were returning very small data sets to filter. In the end, it comes down to how complex your logic is (can it be expressed in SQL and still understood?), how performant each option would be, and how scalable the solution would be.

There are also a number of good ORM's out there that can help blur the line between your business logic and data access. Many of them will dynamically create the complex SQL based on your code, so there isn't as much of a concern about how ugly it'll be.

于 2012-06-27T10:31:17.767 回答