On Mon, Mar 3, 2014 at 11:14 AM, Brandon <
wong...@gmail.com> wrote:
> So I assumed that getting an Order list from User
> should be a method placed inside Order.
Not necessarily, though it will have to interact with Order at some
point. Getting a User's Orders should be as simple as user.orders,
assuming orders belong_to users.
> Then I noticed it expects to get param[:id] as User.id
Things like this are usually changeable.
> so I was tempted to put it back to User (the God
> object). How do reckon I solve this Order list problem?
IIRC you were after a list of users who have ordered, right? The
immediately obvious solution would be something like "User.all.select
{ |u| u.orders.any? }", but that would have horrible performance as it
would fetch the orders for each user in a separate query (N+1
problem). Better would be "User.where(id:
Order.pluck(:user_id).uniq)", which would do one query to get the IDs
and one to turn them into users. There's probably also some AR syntax
to have the DB do the uniq'ing for you, without stooping to
hand-rolled SQL, but I forget it offhand.
> I've been reading a lot about Slim Controller, Fat Model and now looking at
> my codebase with new lenses
Here, let me grind down those lenses a bit more. :-) The models
shouldn't be horribly fat either, it's just that it's a *better* place
for business logic than the controller, never mind the view. If a
model is getting unwieldy, you can possibly extract a service object,
or a data object, or some other thing, from it. Let the Single
Responsibility Principle be your guide.