3

I am new to Ruby on Rails and I have basic knowledge of mysql. I am using MySQL db. My question is -- how to check if a row is exists or not in a table. I have tried this code but it's not going straight to the else block, not the if block:

@tasks = User.find_by("user_name = ? AND password = ?", params[:user_name], params[:password])
if @tasks
  redirect_to action: 'index', status: 302
else
  redirect_to action: 'detail', status: 302
end
Sariban D'Cl
  • 2,197
  • 2
  • 28
  • 42

3 Answers3

2

If you want to find if a user with the given name and password exists using Ruby on Rails, then you can do this:

User.where(user_name: params[:user_name], password: params[:password]).exists?

See the RailsGuides: Existence of Objects.

The Cause of the Original Problem?

So this it the code that the original poster originally submitted:

User.find_by("user_name = ? AND password = ?", "#{params[:user_name]}", "#{params[:password]}")

I removed the string interpolation because it was unnecessary

User.find_by("user_name = ? AND password = ?", params[:user_name], params[:password])

and apparently that fixed the problem. I'm not sure why it would make a difference though, the interpolated string should be the same value as the values in the params dictionary.

Community
  • 1
  • 1
2

You can use any of these solutions depending on your requirement.

Sol-1:

User.where(user_name: params[:user_name], password: params[:password]).exists?

Sol-2:

User.find_by_user_name_and_password(params[:user_name], params[:password])
  • where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation.

  • find (and its related dynamic find_by_columnname methods) returns a single model object, or possibly a collection of model objects in an Array (not a Relation). If nothing is found, an ActiveRecord::RecordNotFound exception is raised.

So yes, if you only want and expect a single object, using find is easier, as otherwise you must call Model.where.first.

Vamsi Krishna
  • 3,742
  • 4
  • 20
  • 45
1

you can try it as well..

User.find_by_user_name_and_password(params[:user_name], params[:password])

PythonDev
  • 4,287
  • 6
  • 32
  • 39