Topic: Getting data from a view

Hi guys, I'm new here and to RoR. I'm a J2EE developer during the day so I'm not new to programming. I find myself thinking "I know exactly how to do this in Java, now how do I do it in Ruby?"

This is something really simple so I understand how things are done in Ruby vs. Java. I have a login form and once the user clicks submit, I want to print the username and password in the console.

<%= start_form_tag :action => 'login', :theUser => @user %>
    Username <%= text_field ("user", "username", :size => 10) %> <br />
    Password  <%= text_field ("user", "passwd", :size => 10) %> <br />
    <%= submit_tag "login" %>

    <%= link_to "check it out", :action => "switch", :theUser => @user %>
<% end_form_tag %>


def
    login = params[:user]
    puts login.username
    puts login.passwd
end

I run the app and get this exception

NoMethodError in AdminController#login
undefined method `username' for {"passwd"=>"XXXXXX", "username"=>"OOOOOOOOOOO"}:HashWithIndifferentAccess

Thanks for the help!

Last edited by JackBauer (2006-08-26 02:39:05)

Re: Getting data from a view

The 'params' object is a hash, so it needs to be acessed by keys, not method calls.  If you created a User object based on the params you could access them like you are (with user.username and such).

But in your example you're looking for:

def login
  login = params[:user]
  puts login[:username]
  puts login[:passwd]
end

Out of curiosty, why do you want it printed to the console?  If you're just trying to debug there are other ways.  For example, here's a quick and easy way to print something to your browser:
raise params.to_yaml

Re: Getting data from a view

Ah thank you! I'm just figuring out Ruby syntax and see how it works. Printing to console seemed to be a quick and dirty way examining values inside a parameter that I knew of.

Last edited by JackBauer (2006-08-26 11:02:58)

Re: Getting data from a view

FYI, since you're probably more used to OO, you could also say.

def 
  login = User.new(params[:user])
  puts login.username
  puts login.passwd
end