user3726986
user3726986

Reputation:

Rails 4: Fetch Data By Column Name Rails Error

I want to fetch data from db based on some search string. But I am getting the exception

undefined method `find_all_by_client_name' for ...

Can someone tell what's the issue with the code?

@workout_schedules = WorkoutSchedule.find_all_by_client_name(params[:search_string])

Following is the schema for workschedule

ActiveRecord::Schema.define(version: 20140804052924) do

  create_table "workout_schedules", force: true do |t|
    t.string   "client_name"
    t.string   "trainer"
    t.integer  "duration_mins"
    t.date     "date_of_workout"
    t.decimal  "paid_amount"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

Upvotes: 0

Views: 104

Answers (1)

RAJ
RAJ

Reputation: 9747

In Rails 4.1, find_by_<column_name> and find_all_by_<column_name> methods got removed.

In the 4.1 release notes:

Removed activerecord-deprecated_finders as a dependency. Please see the gem README for more info.

You can achieve the desired result by using where:

@workout_schedules = WorkoutSchedule.where(:client_name => params[:search_string])

I strongly recommend where over find_by. In attribute based finders imposes extra overhead on your query.

Still if you want to use these finders. You can use activerecord-deprecated_finders gem to regain the finders feature.

Cheers!

Edit:

If you want to search by multiple columns, you can use where like this:

search_string = params[:search_string]
@workout_schedules = WorkoutSchedule.where(["trainer = ? OR client_name = ?", search_string, search_string])

Upvotes: 2

Related Questions