activerecord

How to join an indirect association in ActiveRecord query in Ruby on Rails?

这一生的挚爱 提交于 2019-12-14 01:41:09
问题 In my Ruby on Rails application, I have a model Instance which belongs to another model Zone . The Zone model itself belongs to Country model. I am fetching a set of Instance objects as follows: scope :thisweek, -> { joins(:zone).where(zones: {created_at: ...}).includes(:zone) I would like to join Country to Zone and Instance as well, and then sort the result Instance set based on the zone.country.name field. Anyone can help me please? 回答1: You can try the following: scope :this_week, proc do

How to implement `upsert` for PostgreSQL in ActiveRecord?

前提是你 提交于 2019-12-14 01:36:58
问题 I have a stream of data, which contains categories. I want to maintain a Category table which should contain every category I encounter exactly once. I want to implement a id = Category.upsert(name) , which should be atomic (of course), and - if possible - not use stored procedures on the DB side. 回答1: The upsert gem seems to do just that - I found it while googling to see if "upsert" is a thing. 回答2: How about this: class Category < ActiveRecord::Base ... class << self def upsert(name)

Rails first_or_create adds (1=2) to query

孤街浪徒 提交于 2019-12-14 01:30:06
问题 While running development code through Heroku console in sandbox mode, I use first_or_create to test for existence of a record: Right.where(:language => language ). where(:work_id => work_id ). where(:contact_id => contact_id ). first_or_create! The query to test for existence of the record gets an extra predicate (1=2) added to it, so the record is not found. SELECT "rights".* FROM "rights" WHERE "rights"."language" = 'ger' AND "rights"."work_id" = 625 AND "rights"."contact_id" = 1435 AND (1

Ruby On Rails: Initialize object with random GUID on “.new”?

依然范特西╮ 提交于 2019-12-14 01:29:19
问题 I'm new to Ruby & Rails... the goal is to create a User class whose primary key ( id ) is not an integer, but a GUID. I think I have the ActiveRecord end of things setup properly (not auto-generating an id column with type integer , but with column id of type string instead), and a function that can generate a GUID. The only missing piece at this point is getting Rails to initialize a new User class' with an id using the *generate_guid* function I had wrote. My question : How do I get Rails

Ruby on Rails Active Record RANDOM() always the same within a loop

僤鯓⒐⒋嵵緔 提交于 2019-12-14 01:26:18
问题 Why does this output the same record ID repeatedly, when it should be grabbing a random record each loop iteration? count = 0 while count < 20 puts "ID: " + SomeModel.where(assoc_id: 10).order("RANDOM()").limit(1).first.id.to_s count += 1 end Output: ID: 82784 ID: 82784 ID: 82784 ID: 82784 ID: 82784 I have already ensured there are sufficient records available with the query (ie more than 1). Within a console, the line by itself (outside of a loop) will return a new ID every time, so it has

Difference between size, length and count in complicated ActiveRecord case

拜拜、爱过 提交于 2019-12-14 01:18:47
问题 [10] pry(main)> r.respondents.select(:name).uniq.size (1.1ms) SELECT DISTINCT COUNT("respondents"."name") FROM "respondents" INNER JOIN "values" ON "respondents"."id" = "values"."respondent_id" WHERE "values"."round_id" = 37 => 495 [11] pry(main)> r.respondents.select(:name).uniq.length Respondent Load (1.1ms) SELECT DISTINCT name FROM "respondents" INNER JOIN "values" ON "respondents"."id" = "values"."respondent_id" WHERE "values"."round_id" = 37 => 6 Why the difference in what each query

Find ActiveRecord object by maximum field value of a child object?

谁都会走 提交于 2019-12-14 00:16:20
问题 How can I find the object associated with the results of an ActiveRecord Calculation rather than a value? For example I have @parent which has many children. I would like to find the child with the maximum 'value'. I understand that I can do @parent.children.maximum(:value), but this returns the maximum value. Is there a method similar to maximum and minimum that returns the entire object instead of the value so that I can use different fields from the maximum object? 回答1: @parent.children

Rails: Filter based on multiple params?

心不动则不痛 提交于 2019-12-13 21:04:52
问题 I have a simple app and the user can filter based on three different params by category, by discipline and by target group. All params are optional. So far it works, but the controller below is a bit bloated and I also think the three if statements are a bit messy. Is there a cleaner way to do this? def index @listings = Listing.includes(:categorizations, :listing_disciplines, :listing_targets).page(params[:page]) if params[:category_id].present? && params[:category_id] != "" @category_id =

Cannot use group with has_many through in Rails 5

杀马特。学长 韩版系。学妹 提交于 2019-12-13 20:27:01
问题 I have the following associations: class Student < ApplicationRecord has_many :people_schools has_many :schools, through: :people_schools end class PeopleSchool < ApplicationRecord belongs_to :student belongs_to :school end class School < ApplicationRecord has_many :people_schools has_many :students, through: :people_schools end I am trying to get a list of students organized by their school. I have tried the following: Student.joins(:schools).all.group('schools.name') but I get the following

ActiveRecord with different Date/Time format

依然范特西╮ 提交于 2019-12-13 20:11:03
问题 We have an application where user sets his/her preferred date/time format. User is expected to enter datetime in configured format across the application. Now the problem is for few formats the datetime is parsed wrongly while create/update ActiveRecord . For example user has set date/time format in hh:mm dd/MM/yyyy . Now if user enters 17:00 04/05/2012 it parses it as 5 PM 5 Apr, 2012 where it should be 5 PM 4 May, 2012 1.8.7 :004 > a = Article.create!(:name => 'a1', :published_at => '17:00