Question

I'm trying to get a messaging feature working (using the acts-as-messageable gem) and I want a user to send a message without having to enter a ':to' field.

In my /users/show.html.erb I have:

<%= link_to 'Send a message', new_message_path %>

And in my /messages/new.html.erb:

<%= simple_form_for @message, :url => messages_path, :method => :post do |f| %>
   <%= hidden_field_tag :user_id %> 
   <%= f.input :body %>
   <%= f.submit %>
 <% end %>

And my messages controller:

def new
  @message = ActsAsMessageAble::Message.new
 end

 def create
   @to = User.find(params[:user_id])
   current_user.send_message(@to, params[:body])
 end

At the moment when I submit the form, Rails obviously can't find a user with id= nothing since there is no param[:user_id] present.

I can't figure out how to pass the param into that hidden_field_tag in the form?

Appreciate your help.

Was it helpful?

Solution

So what I wanted to do was visit a users profile, click send message, and be able to write the the message and let it send automatically to the user without explicitly stipulating a :to field.

The problem was that :user_id in <%= hidden_tag_field :user_id %> wasn't being set. In other words, I couldn't get :user_id from the params while in that form.

Some of the solutions we tried were to include the params in the link_to but that didn't sit well with the form which saw the object as nil.

What I ended up doing was creating a nested resource like so:

resources :users do
   resources :messages do
   end
 end

And this ultimately gave me the url: users/:id/messages/new (new_user_message_path)

My controller ended up looking like this:

def new
   @message = ActsAsMessageable::Message.new
   @user = params[:user_id]
 end

 def create
   @to = User.find params[:id]
   if current_user.send_message(@to, params[:acts_as_messageable_message][:body]
     flash[:notice] = "Success"
   else 
     flash[:error] = "Fail"
   end
 end

In the form I was able to leave <%= hidden_tag_field :user_id %> as is.

But basically that solved the problem of finding the user (whose profile I was visiting) and setting the @to in my create action.

OTHER TIPS

I'm on my iPhone so sorry for the brief reply, you just need to pass in the user id into the hidden field, you can find the syntax in the answer here:

rails - what exactly does hidden_field and hidden_field_tag do?

Edit: just noticed - this    <%= hidden_field_tag :user_id %>

Should be this:    <%= f.hidden_field_tag :user_id %>

Try passing the params into the create method like this:

User.find(params[:message][:user_id])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top