Maki
Maki

Reputation: 913

Get data from form params

I'm new for rails and ruby. I try to make a simple project and have this problem. I have a view with some text fields on it, when I press submit button, in my controller I need the values from this fields as strings, I try this way params[:field1], but the value is in this format {"field1"=>"some_value"}, it's not a string and I have the problems with it. How can I solve it?

UP: view code

<%= form_tag :action=>:login_user do %>
    <div class="field">
        <h2>Login</h2>
        <%= text_field "field1", "field1" %>
    </div>

    <div class="field">
        <h2>Password</h2>
        <%= password_field "field2", "field2" %>
    </div>

    <div class="actions">
        <%= submit_tag "Login" %>
    </div>

    <% end %>

Upvotes: 4

Views: 26544

Answers (3)

Ashish
Ashish

Reputation: 5791

Try to use like this:

<%= text_field_tag "field1" %>
<%= password_field_tag "field2" %>

Upvotes: 5

rubyprince
rubyprince

Reputation: 17793

Using the code you have pasted you will have to access it as params[:field1][:field1] and params[:field2][:field2]. So as Ashish suggested you should use text_field_tag. Or in the conventional way of Rails, use form_for to bind both the fields to a single key and use update_attributes or create.

Upvotes: 1

fl00r
fl00r

Reputation: 83680

params[:field1]

is correct way.

Your params is a hash:

params => {"field1"=>"some_value"}

so to get field1 you should call params[:field1]

UPD

For your structure (that is actaully bad) you should call for params this way:

params[:field1][:field1]
params[:field2][:field2]

better to use text_field_tag and password_field_tag in your case:

<%= text_field_tag :field1 %>
<%= password_field_tag :field2 %>

Upvotes: 6

Related Questions