0

I am developing an API in Rails 3 and I got a user model and a message model. I want the developer to be able to get all info about the user as well as the last message from the user. How can I do this? How can I "include" the messages into the user output?

How can this code be modified to suit my purpose?

def index

    @contacts = current_user.contacts

    @users = Array.new

    @messages = Array.new

    @contacts.each do |contact|

        user = User.find(contact.friend_id)

        @users << user

        message = Message.find_by_user_id(contact.friend_id)

        @messages << message

    end

    respond_to do |format|

        format.html { render :text => 'Use either JSON or XML' }
        format.json { render :json => @users }
        format.xml { render :xml => @users }

    end

end

Thankful for all input!

1 Answer 1

1

You should take advantage of your model, and include the last message as a method in your User model. You can then use the :methods hash of the render method.

  format.json { render :json => @users , :methods => [:last_message]}

EDIT

Your user model should be something like:

def User < ActiveRecord::Base
  has_many :messages
  attr_accessor :name, :email #Include the fields you wish to show here

  def last_message
    self.messages.first
  end
end

And your controller:

def index

    @contacts = current_user.contacts

    respond_to do |format|

        format.html { render :text => 'Use either JSON or XML' }
        format.json { render :json => @contacts, :methods => :last_message }
        format.xml { render :xml => @contacts, :methods => :last_message }

    end

end
Sign up to request clarification or add additional context in comments.

9 Comments

Sounds interesting! What should I write in the user model to get the last message? I am not sure how I should do that. Could you show me?
I know how to use what you propose and that is awesome. The only problem now is I want to get the messages per person. How can I send parameters to the user model method? Please help!
See my edits, let me know if there is anything unclear. I would check how many SQL queries it is making, if it is required, there are some optimisations that could be made.
Getting clearer. Unfortunately I get errors: NameError (undefined local variable or method `this'.
Apologies, that should have been self.messages.first, if that doesn't work, try just messages.first.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.