rails 4 conditions where value from table - ruby-on-rails

I have created a table with a attribute called category. The category has different values 'airport', 'sights' ect.
How can i find all locations in the category 'sights' ?
i tried this:
#sights_markers = Location.where(:category = 'sights')
and this
#sights_markers = Location.where('category = sights')
and this
#sights_markers = Location.where('category = sights')
but this give me a error.
Please advise..thanks..remco

Its simple,
#sights_markers = Location.where(category: 'sights')
Please read this at least once. http://guides.rubyonrails.org/active_record_querying.html

you have make a mistake, do like this,it will work:
#sights_markers = Location.where(:category => 'sights')
or
#sights_markers = Location.where("category = 'sights'")

Related

How do I generate an ActiveRecord Relation and make sure to include specific objects within the collection?

I want to generate an ActiveRecord relation that looks like this:
#profiles = Profile.published.order("RANDOM()").limit(8) + Profile.where(demo_linked: true)
The issue with the above is that it returns an array, which is what I don't want.
I would like the above to be an ActiveRecord relation.
Thoughts?
As described in the guides:
random_published_profiles = Profile.published.order("RANDOM()").limit(8)
demo_linked_profiles = Profile.where(demo_linked: true)
all_profiles = random_published_profiles.merge(demo_linked_profiles)
I eventually got it with the following:
#selected_profile = Profile.published.where(demo_linked: true)
#random_profiles = Profile.published.order("RANDOM()").limit(8).where.not(id: #selected_profile.pluck(:id))
#profiles = #random_profiles + #selected_profile

Filterring ActiveRecord Relation...if there are no matches. (Null the active record relation)

I have a dashboard that allows for filtering of the results by different parameters. I build methods to filter the results by the given criteria. One area where I'm having trouble is if the previous line should null out the active record relation. Should I just put a bunch of if present? stat
def find_website_stats(options = {})
if options[:date_between].present?
start_date = options[:date_between].split(/-/).first.to_date
end_date = options[:date_between].split(/-/).last.to_date + 1
elsif options[:start_date].present?
start_date = options[:start_date].to_date
end_date = options[:end_date].to_date + 1 if options[:end_date].present?
end
contractor_name = options[:search_contractor] if options[:search_contractor].present?
distributor_name = options[:search_distributor] if options[:search_distributor].present?
distributor_ids = options[:with_distributor] if options[:with_distributor].present?
contractor_ids = options[:with_contractor] if options[:with_contractor].present?
with_country = options[:with_country] if options[:with_country].present?
with_state = options[:with_state] if options[:with_state].present?
search_city = options[:search_city] if options[:search_city].present?
web_stats = self.website_stats
if web_stats.present?
web_stats = web_stats.where(contractor_id: [*contractor_ids]) if contractor_ids.present?
if distributor_ids.present?
web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*distributor_ids]).pluck(:website_stat_id)
web_stats = web_stats.where(id: [*web_stat_ids])
end
web_stats = web_stats.where(date_recorded: start_date..end_date) if start_date.present? && end_date.present?
web_stats = web_stats.with_country(with_country) if with_country.present?
web_stats = web_stats.with_state(with_state) if with_state.present?
web_stats = web_stats.search_city(search_city) if search_city.present?
#untested
if contractor_name.present?
searched_contractor_ids = Brand.search_contractor(contractor_name).pluck(:id)
web_stats = web_stats.where(contractor_id: [*searched_contractor_ids])
end
if distributor_name.present?
searched_distributor_ids = Brand.search_distributor(distributor_name).pluck(:id)
web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*searched_distributor_ids])
web_stats = web_stats.where(id: [*web_stat_ids])
end
#end untested
end
web_stats
end
Where I'm specifically having a problem right now is the line that says if web_stat_ids.present?
So at first I grab all the website stats this object is associated with and then look to see if there are any for the given distributor.
If there is none for the given distributor web_stat_ids obviously returns nil
Then when I go to the line web_stats.where(id: [*web_stat_ids]) that's obviously going to return the same thing that I had before, rather than an empty active record relation, which is what I need it to be?
If I make this an empty array the next few statements with "where" won't work because it's an array and not an active record relation.
I know I can wrap this stuff in a bunch of if present? && statements...but I was wondering if there is a better solution to my problem?
In case anyone else is looking for this, found the answer from this SO post: How to return an empty ActiveRecord relation?
Model.none rails 4+

Query Rails Postgres with array data type

So, Ive been trying to query my PostgreSQL model in Rails, but get the following error:
undefined method `id' for TransactionTemplate::ActiveRecord_Relation
My code:
#transaction_templates = TransactionTemplate.where("transaction_category_id = 1")
#transaction = Transaction.where("transaction_template_id in (?)", #transaction_templates.id)
I know that the transaction templates is an array and that there is therefor not just one ID it needs to look up, but multiple of IDs, just as I want it.
Any suggestions?
Try this:
#transaction_templates = TransactionTemplate.where("transaction_category_id = 1")
#transaction = Transaction.where("transaction_template_id in (?)", #transaction_templates.map(&:id))
If you need just ids then try:
#transaction_template_ids = TransactionTemplate.where("transaction_category_id = 1").pluck(:id)
#transaction = Transaction.where("transaction_template_id in (?)", #transaction_template_ids)
Or you have proper associations then
#transaction = Transaction.joins(:transaction_template).where("transaction_category_id = 1")

save information from another table

Hi everyone at this time i have two tables:
clientesultimasgestiones
clientesgestiones
And I want to put the whole information from clientesgestiones to clientesultimasgestiones but I want to save it field by field, at this momento I have this
cnx = ActiveRecord::Base.connection
cnx.execute("truncate table clientesultimasgestiones")
#informacion = Clientesgestion.all
#informacion.each do |f|
#clientesultimasgestion = Clientesultimasgestion.new
#clientesultimasgestion.save(f)
Here will be the code to save field by field from clientesgestiones table to the another one
end
Thanks for your help
EDIT: Finally i did it this way:
cnx.execute("truncate table clientesultimasgestiones")
#informacion = Clientesgestion.all
#informacion.each do |f|
l = Clientesultimasgestion.new
l.persona_id = f.persona_id
l.fecha_gestion = f.fecha_gestion
l.clientestipologia_id = f.clientestipologia_id
l.observacion = f.observacion
l.user_id = f.user_id
l.fecha_acuerdo = f.fecha_acuerdo
l.valor_apagar = f.valor_apagar
l.clientestipologiaanterior_id = f.clientestipologiaanterior_id
l.clientesobligacion_id = f.clientesobligacion_id
l.save
end
Thanks a lot :)
I would replace:
#clientesultimasgestion.save(f)
with:
#clientesultimasgestion.update_attibutes(f.attributes)
Also, seems what you want is to copy a table, see https://stackoverflow.com/a/13237661/1197775.
I think this question will help you to get lists of attributes and values.
After this, you need to set dynamically fields, for this purpose you can use method send. Something like this:
#clientesultimasgestion.send("#{field_name}=",field_value)

Ruby loop problems

I am working on a script that is supposed to be writing a list of items to a hash, but for some reason its only placing the last item in the loop in the hash... I have been working on this script all day, so I am pretty sure its something I am just missing.
Here is the script
#mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
#mr.each do |rating|
#m = Media.where("id = ?", rating.media_id)
#m.each do |m|
s = Profile.find_by_subscriber_id(m.subscriber_id)
#h_lang = Language.find_by_code(s.language)
#history = {m.title => #h_lang.english}
end
end
There are multiple records in the MediaRating table so I know it has to do something with how my loop is. Thanks in advance for the help!
Working code:
#mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
#mr.each do |rating|
#m = Media.find(rating.media_id)
s = Profile.find_by_subscriber_id(#m.subscriber_id)
#h_lang = Language.find_by_code(s.language)
#history[#m.title] = #h_lang.english
end
In the last line, you are over-writing the entire #history hash instead of adding a new key/value pair to it. I'm guessing that isn't what you intended. Change this line:
#history = {m.title => #h_lang.english}
to this:
#history[m.title] = #h_lang.english

Resources