0

I have model User. And one of controller methods is

 def view_messages
    @user = User.find(params[:id])
    @message=Message.new
    @[email protected]
  end

Also i have model Message , and one of parametres of this model is user_from:integer

view_messages view have

render :partial => 'messages/message', :collection => @messages

and _message.haml have

= content_tag_for(:li,message) do
  %p
    From:
    =link_to User.find(message.user_from).name,User.find(message.user_from)

it writes an error

Couldn't find User without an ID

but if i want to print it like

 = content_tag_for(:li,message) do
      %p
        From:
        =message.user_from

it print it ( for exaple it prints 2) , so why it cant find user with id 2 if i have this user? What i am doing wrong? Thanks in advance

2
  • please help. very need to solve this problem Commented Oct 30, 2011 at 14:13
  • How does @user.messages work? I guess it's not a has_many relation, judging from your code. Commented Oct 30, 2011 at 14:59

1 Answer 1

2

General issues:

  1. user_from should be user_from_id, by Rails convention

  2. Then you should have a belongs_to relation:

    class Message
      belongs_to :user_from
    end
    

    which will automatically pull the user from the database

  3. Then you can refer to the user as an attribute of Message

    link_to @message.user_from.name, @message.user_from
    

Check all of the Message records. One of them probably has no user_from, and causes the error.

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

3 Comments

thanks. i am newbie / i will try to follow all ruby conventions. You were right,i needed to reset my database, cause old messages didnt had parameter :user_from
and you should do @user = User.find(params[:id]).include(:messages)
generally speaking your current infrastructure is terrible in terms of performance and db queries

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.