Vikram
Vikram

Reputation: 3361

Check form submitted values in ruby on rails

On my rails app I have a form on /addfiles where user can add file path in text boxes and this form is submitted to /remotefiles

I have created a route match '/remotefiles' => 'main#remotefiles'

and function in main controller

def remotefiles
    render layout: false
end

and add remotefiles.html.haml in views/main

how can I show these submitted values on remotefiles, I think it can be done with render but not sure how can I use it to pass form values and show them on view.

Is there a way to check form data in ruby on rails just like php print_r function ?

Upvotes: 0

Views: 1461

Answers (1)

Kristján
Kristján

Reputation: 18813

Your form data is coming in via the params hash. The simplest way to respond with it would be

# MainController
def remotefiles
  render json: params
end

If your form contained fields named foo and bar, you'll see those as well as some parameters Rails adds:

{
  "foo": 1,
  "bar": 2,
  "controller": "Main",
  "action": "remotefiles"
}

If you want to render them into a real template, write the HTML into app/views/main/remotefiles.html.erb. Rails will by default render a template matching your controller and action, or if you want a different one you can instruct Rails to render "path/to/other/template". Your template can access params too, but the more typical way to pass data into them is by setting instance variables in the controller.

# MainController
def remotefiles
  @foo = params[:foo]
  @bar = params[:bar]
end

# app/views/main/remotefiles.html.erb
<strong>Foo</strong> is <%= @foo %>
<strong>Bar</strong> is <%= @bar %>

Lastly, if you don't actually want to render the form data back to the browser, just inspect it during development, Rails.logger will print it into your server log.

# MainController
def remotefiles
  Rails.logger.info(params[:foo], params[:bar])
end

You should read up on how Rails works - the getting started guides are very clear and helpful. Here's the one on rendering.

Upvotes: 1

Related Questions