0

I am trying to do something simple: in my Rails view, I have a text input that I want to capture and append to the params. I found a similar question, but I want to know if I can do it inline without updating the controller.

First, in the view, I have a form input and a Rails link. These work independently right now for testing, but I can pass the username as a param on button click:

<form>
    <input type="text" name="name">
 </form>    
    <%= button_to 'Call Action', points_path(username: @current_user.last.username), method: :post %>

I want to remove the @current_user.last.username and instead pass what the user has typed in the input as a param.

Is there a way to do this without a subaction, as outlined above, in the controller (either through a helper or using Javascript with my Rails link)?

Community
  • 1
  • 1
darkginger
  • 652
  • 1
  • 10
  • 38

2 Answers2

3

You are trying to submit a form, let's do it in Rails way,

<%= form_for :points, points_path do |f|  %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

In the action you can access the name param by params[:points][:name]

Hope that helps!

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • 1
    Hey, I think the logic of your answer makes sense, and I should do it the Rails way. When I make those updates and load the view, I am getting an error for `undefined method `[]' for nil:NilClass`. I am wondering if my `:points` is an issue, since I am not actually sending data to the database -- I am just trying to append it to the params. Will report back if I figure it out. – darkginger Apr 22 '16 at 06:39
1
  1. Attach a javascript click event to the button that prevents the default behaviour.
    • In your click event, fetch the value of the input element and append it to the url var go_to = "/path/to/action?param_name=" + input_value.
  2. Then redirect to that url.

It looks like you're using the post method, so you could check out JavaScript post request like a form submit with instructions on how to post from JavaScript without using ajax - in a nutshell you make a form on the fly and submit it.

Edit

@RSB's got it right - that's the rails way to do it. If you insist on using a button and a standalone input instead of a form, you can do it the way I described... but I think you're better off following @RSB's advice.

Community
  • 1
  • 1
alexanderbird
  • 3,847
  • 1
  • 26
  • 35