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.
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:
And this ultimately gave me the url: users/:id/messages/new (
new_user_message_path)My controller ended up looking like this:
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.