Reputation: 892
I'm creating a messaging system of sorts. It's part of a bigger overall system in Rails 4. Anyway, to setup my question briefly I have users who can both send and receive messages. So in my "new" users' view I send a parameter [:receiver_id] to the message controller when creating a new message.
My question is how do I get the @send_to variable down to the create action properly. I had to send it into the messages@new action via the receiver_id from the users' view. Do I store it as a message parameter somehow or make it a hidden parameter?
Here is my messages controller
class MessagesController < ApplicationController
def new
@message = Message.new
#this :receiver_id is being sent from the show view in the user controller / view
#it is being used to pass a parameter
@send_to = User.find(params[:receiver_id])
@message.sender = current_user
@message.receiver = @send_to
#the form_for should save the message with the RESTful action of create method in this controller
end
def create
debugger
@messasge = Message.create!(message_params)
redirect_to users_path
end
def index
@messages = current_user.messages
end
def sent
@messages = current_user.messages
end
def message_params
params.require(:message).permit!
end
end
I know from rails routing mostly about RESTful actions, and yes I have read over the routing guide again before writing this.
I have moved these two lines down into the create function. The @send_to needs the :receiver_id though.
@message.sender = current_user
@message.receiver = @send_to
Upvotes: 0
Views: 46
Reputation: 3243
messages#create
action. I assume that user, while fulfilling form data, can select somehow message recipient.new
does not need to know who is the message receiver.Message.create!
(with !
) because it will raise an exception if creation fails. Use save
instead and handle case if it would fail, e.g:
def create
@message = Message.new params[:message]
@message.save
respond_to do |f|
f.json do
render :json => {:success => @message.persisted?, :message => @message}.to_json
end
end
end
Upvotes: 1