views:

93

answers:

3

I have body:text content:text sender_id:integer receiver_id:integer in message table

I have this in user model:

   has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
   has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"

I have this in message model:

   belongs_to :sender, :class_name=>"User", :foreign_key=>"sender_id"
   belongs_to :receiver, :class_name=>"User", :foreign_key=>"receiver_id"

After logging while you are viewing the other user's profile (I mean this link in users view).

I call new message like this:

  <%= link_to "Send a Message",{:controller=>"messages",:action=>"new"}%>

I have these codes in messages_controller:

 def new
  @message = current_user.sent_messages.build
   end

def create
@message = current_user.sent_messages.build(params[:message])
  if @message.save
  flash[:notice] = "Successfully created message."
  redirect_to root_url
else
  render :action => 'new'
 end
 end
#.....

Also I have these codes in views\messages\new.html.erb

 <% form_for @message do |f| %>
 <%= f.error_messages %>
  <p>
 <%= f.label :body %><br />
 <%= f.text_field :body %>
  </p>
  <p>
 <%= f.label :content %><br />
 <%= f.text_area :content %>
  </p>
 <p><%= f.submit "Submit" %></p>
  <% end %>

After clicking link I fill body and text then submit. Everything is saved but receiver_id value is null. I tried many things to do but I couldn't save receiver_id

For ex: I set link like that:

  <%= link_to "Send a Message",{:controller=>"messages",:action=>"new",
   :receiver_id=>@user.id}%>

It sends the user id which I want and I can get this value with params but the problem is I couldn't find a way to save this value to database while saving the others.

A: 

Passing receiver_id in the params just gives the new method access to it. You'll need to access and store params[:receiver_id] somewhere in your new method.

Chuck
I know but how ?
A: 

Lol I found I call new message like I mentioned before

 <%= link_to "Send a Message",{:controller=>"messages",:action=>"new",
 :receiver_id=>@user}%>

then new method will be like that in message model

 def new
 @message =current_user.sent_messages.build(:receiver_id=>params[:receiver_id])
  end

And the simplest thing(actual it's the big problem for me :)) in views/messages/new.html.erb add this line in form_for

 <%= f.hidden_field :receiver_id  %>
A: 

try

class MessagesController
   def new
     @message = current_user.sent_messages.build :receiver_id => params[:receiver_id]
   end    
end

personally I like to use nested routes in the url like so

domain/users/123/messages/new

then you can do

link_to "Send a message", new_user_message( @user )

so your controller would say

class MessagesController
   def new
     @message = current_user.sent_messages.build :receiver_id => params[:user_id]
   end    
end
austinfromboston