I have jobplacement model and i want to implement search functionality which should be a keyword search i.e i mean even if you type any keyword in search and if that is present in the db of jobplacement table it should show the results.
Currently i am using following code which just matches 1 field i.e name of the company and category as in the params[:category].Following is tha code of my jobplacementcontroller/index action
if params[:search]
#search_condition = "%" + params[:search] + "%"
#searchresult = Jobplacement.where(['name LIKE ? and category = ?', #search_condition ,params[:category]])
else
#searchresult = ""
end
Also in above code although i have given condition for category its not executing properly.When i do search it gives results that matches name field but its not evaluating params[:category] condition.it shows all the records even if they are not in the params[:category].
Following are the fields in my jobplacement model :
t.string "name"
t.string "designation"
t.string "qualification"
t.integer "years_of_exp"
t.string "location"
t.integer "noofpost"
t.string "jobprofile"
t.string "salaryoffered"
t.string "contactperson"
t.string "employmenttype"
t.text "address"
t.string "city"
t.string "state"
t.string "country"
t.integer "contactno"
t.string "website"
t.text "aboutcompany"
so when i enter any keyword in search if that matches with data of any field it should return that data.How can i do this...
How can i solve this params[:category] error and how can i do keyword search that matches any record present in the database of jobplacement model not just 1 field.
check out Thinking Sphinx, it has solutions to your problems and has more features like sub string search, wild char support and more
using the squeel gem http://erniemiller.org/projects/squeel/
you can simply do:
terms = params[:search].split
Jobplacement.where {name.eq(params[:category]) & (name.like_any(terms) | designation.like_any(terms) | qualification.like_any(terms) <...>) }
Related
I'm trying to seed some data using an external trivia API.
Here's what I have in my seeds.rb file where HTTParty is a gem that parses JSON into a ruby hash:
response = HTTParty.get("THE-API-SITE")
response.each do |trivia|
triviaHash = {
category: trivia["category"],
answer: trivia["correctAnswer"],
incorrect: trivia["incorrectAnswers"],
question: trivia["question"],
}
Trivia.find_or_create_by(triviaHash)
end
And here's my schema:
create_table "trivia", force: :cascade do |t|
t.string "category"
t.string "answer"
t.string "incorrect"
t.string "question"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "ids"
end
Everything works except for the "incorrect" key which should have a value of an array of strings of incorrect answers, but when I seed my data, I get a string of the array of incorrect answers.
What I want:
incorrect: ["Deep Purple", "Feeder", "Uriah Heep"],
What I'm getting:
incorrect: "["Deep Purple", "Feeder", "Uriah Heep"]",
I'm not sure how to get what I want or if it's even possible the way I'm going about it.
Since your column incorrect is of type string, so the data stored in DB will also be a string value.
If your DB supports array data type then you can use that or else I would suggest you to use this in your model.
serialize :incorrect, Array
Change your migration field for incorrect field, from:
t.string "incorrect"
to:
t.text :incorrect, array: true, default: []
Also I suggest you to use symbols instead of strings for column names and use t.timestamps that generates created_at and updated_at for you
I am trying to add a date of birth to each patient in my database and having issues adding a date to the dob attribute on each patient. When I add for ex. Patient.first(dob: "01/25/1990") I get an error reading no implicit conversion of Integer into Hash. Any ideas on how I would do so?
create_table "patients", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.integer "age"
t.date "dob"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
When I seeded my database, my dob field was nil
I have also tried Patient.first(dob: Date.parse('31-12-2010')) and still get the same error.
You have two problems:
first doesn't take query arguments.
Your date format is ambiguous.
The first finder method looks like:
first(limit = nil)
Find the first record (or first N records if a parameter is supplied). If no order is defined it will order by primary key.
You want to use find_by as your .where(...).first shortcut.
And to avoid ambiguity with your dates, you should use Date objects or ISO-8601 formatted strings (i.e. YYYY-MM-DD) inside the application and leave the supposedly "human friendly" formats for the very edges.
You want to say:
Patient.find_by(dob: '1990-01-25')
I have the following example:
#ads = Ad.all
I need to sort by popularity so it is based on two integer columns: contacts_count and visualizations.
I want to know if there is any of these options:
1) List first the ads with the most number of contacts and to the records with contacts_count = 0 show the records sorted by visualizations number.
2) Somehow attribute weighs to the two fields like: 5 to contacts and 3 to visualizations or something like that and sort by relevance by this.
How can I do this with active record or any search gem?
schema.rb
create_table "ads", force: :cascade do |t|
t.string "photo"
t.text "description"
t.string "category"
t.integer "user_id"
t.integer "visualizations", default: 0
t.integer "contacts_count", default: 0
t.index ["user_id"], name: "index_ads_on_user_id", using: :btree
end
From what I understood from your description, what you need is not searching but sorting.
Short answer:
#ads = Ad.order(:contacts_count, :visualization)
Wait but why?:
list first the ads with the most number of contacts
order first by contacts
to the records with contacts_count = 0 show the records sorted by visualizations number.
This statement is a bit inaccurate, you will use visualizations as a tiebreaker (even in the case of contacts_count = 0 or just equal contacts_count.
I am getting the error below when trying to query my PostgreSQL database. I can view the table and all columns in pgAdmin and even perform a select *, so I know the table and column exists. Any help with this will be greatly appreciated.
Here is the error I am getting:
PG::Error: ERROR: column "fi_ase" does not exist
Here is the schema for the table in question. It was generated with a migration as part of a Rails 3.2 app.
create_table "certificates", :force => true do |t|
t.integer "profile_id"
t.boolean "FI_ASE"
t.boolean "FI_AME"
t.boolean "FI_INSTA"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "C_ASEL"
t.boolean "C_AMEL"
t.boolean "C_ASES"
t.boolean "C_AMES"
t.boolean "ATP_ASEL"
t.boolean "ATP_AMEL"
t.boolean "ATP_ASES"
t.boolean "ATP_AMES"
t.boolean "GI_Basic"
t.boolean "GI_Advanced"
t.boolean "GI_Instrument"
end
Here is my query/method in Rails:
def self.search(city, state, zip, *certs)
query_obj = joins(:profile => [:addresses, :certificate])
query_obj = query_obj.where("city like ?", "%#{city}%") unless city.blank?
query_obj = query_obj.where("state = ?", state) unless state.blank?
query_obj = query_obj.where("zip like ?", "%#{zip}%") unless zip.blank?
query_obj = query_obj.where("FI_ASE = ?", true) unless certs[0].blank?
query_obj
end
I get the same error when running the following SQL statement directly in my pgAmin SQL Editor:
select *
from contacts c
inner join profiles p on c.id = p.contact_id
inner join addresses a on p.id = a.profile_id
inner join certificates ct on p.id = ct.profile_id
where ct.FI_ASE = true
Rails will double quote the column names when it generates them. For example, the CREATE TABLE for your table will look like this when PostgreSQL sees it:
create table "certificates" (
-- ...
"FI_ASE" boolean,
When an identifier is double quoted, it is case sensitive. But, PostgreSQL will normalize unquoted identifiers to lower case so when you say this:
query_obj.where("FI_ASE = ?", true)
the SQL will come out as:
where FI_ASE = 't'
but, since your FI_ASE is not quoted, PostgreSQL will see that as:
where fi_ase = 't'
However, your table doesn't have an fi_ase column, it has an FI_ASE column.
Now that we know what's wrong, how do we fix it? You can manually quote the column name all the time:
where('"FI_ASE" = ?', true)
or you could let ActiveRecord do it (but make sure you use the right case):
where(:FI_ASE => true)
or best of all, recreate the table using lower case column names so that you don't have to quote things.
I have the following code in my sessions controller which saves information such as Facebook friends, likes, and a user profile to my DB. The profile includes the user's location and gender but it gets saved into the DB as a string so I can't extract it.
#graph = Koala::Facebook::GraphAPI.new(current_user.token)
current_user.profile = #graph.get_object("me")
current_user.likes = #graph.get_connections("me", "likes")
current_user.friends = #graph.get_connections("me", "friends")
current_user.save
Going into the console, I can get the profile of the last user via:
u = User.last.profile
But this doesn't let me call for the location specifically, like:
User.last.profile.location
User table looks like
create_table "users", :force => true do |t|
t.string "provider"
t.string "uid"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "token"
t.string "likes"
t.string "profile"
t.string "location"
t.string "interests"
t.string "birthday"
t.string "activities"
t.string "friends"
end
like this?
graph = Koala::Facebook::API.new(#oauth_token)
#user = graph.get_object("me")
location = #user["location"]["name"]
I am using koala v2.2 and my application Facebook API Version is v2.4.
I did not get location information using just get_object("me") request. I had to pass location as fields parameter like
get_object("me?fields=first_name,last_name,location")
May be this information will be helpful for someone.
N.B: Of course you have to enable user_location scope.
The way I've used to work this out is using scopes and call these scopes in the view, which might not be the best way but is a quick fix.
The User model can be scoped by:
scope :CityName, where("profile like '%location: CityName%'")
to use Facebook Checkins since yesterday e.g.:
unless graph.get_connections('me', 'checkins', :since => 'yesterday').blank?
checkin = graph.get_connections('me', "checkins", :since => 'yesterday')
lat = checkin[0]['place']['location']['latitude']
long = checkin[0]['place']['location']['longitude']