Re: Multiple relations between two models

Chris Mear
Thu, 19 Oct 2006 11:57:56 -0000

Stewart wrote:
> It''s possible I am not as smart as they think I am.
>
> class Message < ActiveRecord::Base
>   belongs_to :sender, :class_name => "User", :foreign_key
=> "user_id"
> end
>
> the above line of code works fine for me when I do something like
> this...
>
> <%= message.sender.full_alpha_name %>
>
> however, when I am trying to create a new message with the following
> code...
>
>   def sendmessage
>     @message = Message.new()
>
>     @message.body = params[:message][:body]
>     @message.title = params[:message][:title]
>     @message.user_id = params[:message][:to]
>     @message.sender = current_user
>
>     if @message.save
>       flash[:notice] = "Message Sent"
>       redirect_to :action => "index"
>     else
>       flash[:notice] = "Message not Sent"
>       redirect_to :action => "index"
>     end
>
>   end
>
> both the sender and the userid are set to the wrong values in the
> database. The sender always has a value of 0 in the database.  The
> userid always has a value of 1.

Hang on. You should only have one column in your ''messages''
table that
relates to this join, and that column should be ''user_id''. You
shouldn''t have a column that called ''sender''.

As far as I can tell, that code should work fine, as long as
current_user contains a saved User object.

When you say "The sender always has a value of 0 in the database.  The
userid always has a value of 1.", exactly which tables and columns are
you talking about?

Chris