camdixon
camdixon

Reputation: 892

Rails 4 | Properly creating and saving in controller

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.

EDIT:

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

Answers (1)

blelump
blelump

Reputation: 3243

  1. You should implement an asynchronous request for sending messages, cause it might be annoying for system users to redirect to another page just to send a message. From the above snippets it is not known (the logic).
  2. Having an asynchronous request, which would serve a dialog with new message form, next step is just to send form data to messages#create action. I assume that user, while fulfilling form data, can select somehow message recipient.
  3. Action new does not need to know who is the message receiver.
  4. Don't use 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

Related Questions