How to pass parameter to hidden_field_tag ​​in my form in Rails 3?

I am trying to use the messaging function (using acts-as-messageable gem) and I want the user to send a message without having to enter the ': 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 message 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 I submit the form, Rails obviously cannot find the user with id = anything, since there is no [: user_id] parameter.

I can’t figure out how to pass the parameter to this hidden_field_tag ​​in the form?

Appreciate your help.

+4
source share
2 answers

So, what I wanted to do was visit the user profile, click "Send message" and write a letter, and it will automatically send it to the user without explicitly specifying a field :.

The problem was that user_id in <%= hidden_tag_field :user_id %> not set. In other words, I could not get: user_id from params while in this form.

Some of the solutions we tried to include included params in link_to, but this did not match the forms that saw the object as nil.

As a result, I created such a nested resource:

 resources :users do resources :messages do end end 

And that eventually gave me the url: users /: id / messages / new ( new_user_message_path )

My controller turned out 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 managed to leave <%= hidden_tag_field :user_id %> as it is.

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

+3
source

I am on my iPhone so sorry for the short answer, you just need to pass the user ID to a hidden field, you can find the syntax in the answer here:

what exactly is hiding_field and hidden_field_tag?

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

Must be: <% = f.hidden_field_tag: user_id%>

Try passing parameters to the create method as follows:

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

+1
source

Source: https://habr.com/ru/post/1399612/


All Articles