Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Which Ruby on Rails active record model method can be used to look for a particular value in the model's column?


Let's say I have a model, Animal, and a column, animal_name. When a user enter chicken, I want to check in the Animal model if there is animal_name "chicken". Assuming the @animal variable carries a value that user entered, how do I check that value exists in the animal_name column?

def check_animal
    if @animal......... #Exists in Animal model
end

Solution

  • Either one of these two forms:

    • Animal.find_by_name("chicken")
    • Animal.where(:name => "chicken")

    Or using a variable:

    • Animal.find_by_name(@animal_name)
    • Animal.where(:name => @animal_name)

    See: