0

I am trying to gather information from a database and then pass that information on to my view via flash. Unfortunately the information is formatting in an ActiveRecord::Relation and not in any format that I can read.

Controller Query

@message = Message.where(:all).limit(4).order(id: :desc).only(:order,:where)    
    flash[:response] = @message
    redirect_to (:back)

If I do something like

@message = Message.where(:all).limit(4).order(id: :desc).only(:order,:where)    
    flash[:response] = @message.first.mess
    redirect_to (:back)

To try and get the first returned value in the mess column, I get an undefined method error. I have been trying to find a tutorial that tells me how to take information once my query has been run but I have not had much luck with Rail's tutorials as of late. I appreciate any help that you guys can give. After I do this I am going to try to format the 4 different results on the view side.

1 Answer 1

1

List of messages:

@messages = Message.order(id: :desc).limit(4)

This: only(:order,:where) cancels your limit(4) (why?)

@messages is now an activerecord association, not suitable to output.... So, if you have 4 messages top you can do:

if @messages.any? # maybe no messages come out
    flash[:response] = @messages.map(&:mess).join('<br>') # add an html newline between them
end
redirect_to :back
Sign up to request clarification or add additional context in comments.

9 Comments

So I understand the query as such - SELECT * FROM Messages ORDER by ID DESC LIMIT 4. However my query is not returning anything (I get the error 'undefined method 'any?' for nil:NilClass') I feel as though I understand the code but then I don't understand why I am not getting any result from the query as the syntax seems fine to me.
Sorry submitted by hitting enter by accident
Do you have a Message class?
Yes a simple one - class Message < ActiveRecord::Base validates :mess, :presence => true validates :user, :presence => true end
Run this in console: Message.order(id: :desc).limit(4), what do you get?
|

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.