views:

45

answers:

2

I have a messages controller thats declared as a resource in my routes.

I want to be able to have a list view of received messages and a different view of sent messages.

But I dont want to break the rest pattern... What do you guys reccomend?

A: 

Keep it simple

/messages?view=sent

In your index method



def index
    @messages = case params[:view]
    when 'sent'
      Messages.sent
    when 'received'
      Messages.received
    else
      Messages.all
    end
end

See how the inherited_resources plugin handles Scoping.

The Who
Sent by whom? Received by whom? Not a complete answer imo. The Questioner also asked it to comply with RESTful practices. This does not. The model is also probably going to be called "Message".
Ryan Bigg
Then NachoF will need to adjust the route to indicate the subject of the request.`/client/73/messages?view=sent`And replace Messages.[all|sent|received] with an appropriate finder.possibly:`client.messages.sent`But in the question NachoF gave no information regarding Message associations.
The Who
And then he would use the params to call send on the messages association? What if I sent those params in as "delete_all"?
Ryan Bigg
The example clearly shows using a `case` statement.
The Who
+3  A: 

in config/routes.rb:

map.resources :messages, :collection => { :sent => :get, :received => :get }

Then in your messages_controller.rb:

def received
  @messages = Message.to(current_user)
end

def sent
  @messages = Message.from(current_user)
end

In your message.rb define these two named scope methods.

Or as Tony Fontenot pointed out:

def received
  @messages = current_user.messages.to
end

def sent
  @messages = current_user.messages.from
end
Ryan Bigg
Wouldn't it be better to do `@messages = current_user.messages.to` and `@messages = current_user.messages.from`
Tony Fontenot
Yeah, you're right.
Ryan Bigg