I am at an absolute loss as to what I am doing wrong with the following code. I am trying to implement a messaging system within my application, but want it to be handle different types of messages. In this case, I want to create a "request" message of ':message_type => 1'.
Instead of using forms as I usually have, I want to make this instance the moment the link is clicked. Here is how I have it set up in the show erb file for "user":
<%=link_to "Send friend request", :action=>"request", :controller => "messages", :id => @user.id %>
and in the controller:
def request
@message = Message.new(:sender_id => current_user.id,:user_id => params[:id],:message_type => 1)
if @message.save
flash[:notice] = 'Message was successfully created.'
redirect_to message_path(@message)
else
redirect_to message_path(@messag开发者_Go百科e)
end
end
This results in the following error message: undefined method `rewrite' for nil:NilClass with the trace looking like
c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/whiny_nil.rb:52:in `method_missing'
c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:634:in `url_for'
(eval):16:in `message_path'
app/controllers/messages_controller.rb:11:in `request'
I have used map.resources :messages in the routes.rb file, and done the appropriate :has_many and :belongs_to associations in the models of user and message.
EDIT: Something else to note is that the save IS succeeding, as once the root address is manually inputted into the address bar, the "flash" notice is shown saying that the save was made. Using the development console it is indeed there, so there's something messed up with the redirect.
You might want to rename the action, I am quite sure that request
means something in the controller.
Why dont you rename the action from request
to create
, and see if it helps.
So the code will be:
In the view
<%=link_to "Send friend request", :action=>"create", :controller => "messages", :id => @user.id %>
In the controller
def create
@message = Message.new(:sender_id => current_user.id,:user_id => params[:id],:message_type => 1)
if @message.save
flash[:notice] = 'Message was successfully created.'
redirect_to message_path(@message)
else
redirect_to message_path(@message)
end
end
Check your logs more closely, and you'll probably find that your save is failing. Not sure which line is #11, but I would guess that it's in your else
block, which tries to build a path for a @message
object with a nil
ID (it hasn't been saved).
精彩评论