ActiveRecord Find with condition based on associated record having a value in a list - sql

With the following Rails models:
class Group < ActiveRecord::Base
has_many :group_locations, :dependent => :restrict
has_many :locations, :through => :group_locations, :dependent => :restrict
end
class Location < ActiveRecord::Base
has_many :group_locations, :dependent => :destroy
has_many :groups, :through => :group_locations
end
class GroupLocation < ActiveRecord::Base
belongs_to :group
belongs_to :location
end
I am trying to Find all of the locations that are associated with at least one of several groups contained in the string "group_list" (e.g. "1,2,3,4,5"). If it was a field from the Location record, I would specify a condition of "*field in (#{group_list})*". But how do I accomplish my goal when I want to have at least one of the location's "group_location" whose "group_id" is in the list (or, alternatively, one "group" whose group_id is in the list).
I know how to do it with pure SQL, but how do you do it with Rails?

#taro You are right. Started by adding the code
joins(:group_locations).where("group_id in (?)", group_id_array)
Then I proceeded to define a scope just to make it a nice package:
scope :locations_in_groups, lambda { |grparray| joins(:group_locations).where("group_id in (?)", grparray) }
Thanks for your help.

Related

How can I reference the same model twice and create the association in a multiple select form?

I have two classes (Game and Report) and want to link them with an additional attribute (default = yes or no).
The game should then have default_reports and optional_reports.
The association is then updated by selecting the default and optional reports in a select (multiple) in the games create/edit form.
I have tried using has_many and through as well as polymorphic associations, but nothing seems to fit the use case, where the associated objects are fixed and you only want to manage associations.
class Game < ActiveRecord::Base
has_many :game_reports
has_many :reports, :through => :game_reports
end
class Report < ActiveRecord::Base
has_many :game_reports
has_many :games, :through => :game_reports
end
class GameReport < ActiveRecord::Base
belongs_to :game
belongs_to :report
end
Any help is appreciated!
Thanks
this is just the model. the view and form to create the records is an entirely different matter.
you can always add a conditions option to has_many. I'm assuming you're going to add default to game_reports so change your class to something like.
class Game < ActiveRecord::Base
has_many :game_reports
has_many :reports, :through => :game_reports
has_many :default_reports, through: :game_reports, source: :report, conditions: { game_reports: { default: true } }
end
Rails 4.2+, use a Polymorphic association with scope and specify the foreign_key and foreign_type options.
class GameReport
belongs_to :report, :polymorphic => true
end
class Game
has_many :game_reports, :as => :report, :dependent => :destroy
has_many :reports, -> { where attachable_type: "GameReport"},
class_name: GameReport, foreign_key: :game_report_id,
foreign_type: :game_report_type, dependent: :destroy
end
Other approachs:
Rails Polymorphic Association with multiple associations on the same model

Use target's scope as a condition of association

I have models like
class Employee < ActiveRecord::Base
belongs_to :branch, :foreign_key => :branch_code, :primary_key => :branch_code,
:conditions => proc{["? BETWEEN enabled_day AND expiration_day", Date.current]}
end
class Branch < ActiveRecord::Base
has_many :employees, :foreign_key => :branch_code, :primary_key => :branch_code
scope :valid, lambda {where(["? BETWEEN enabled_day AND expiration_day", Date.current])}
end
employee belongs to an branch (simple), but branch has several records of same branch_code, and one that is "valid at this moment" should always be used.
(as you may guess, the project is porting of an old app and it succeeds the old schema)
Now, it does work, but I have to write exact same where condition twice (actually branch is associated to more tables, so 5 or 6 times).
wonder if I could use Branch's scope as condition of an association, or any other way to DRY things up?
Would using has_many_through with default_scope work?
Something along the lines of:
class Employee < ActiveRecord::Base
has_many :assignments
has_one :branch, :through => :assignments
end
class Branch < ActiveRecord::Base
has_many :assignments
has_many :employees, :through => :assignments
end
class EmployeeAssignments < ActiveRecord::Base
attr_accessible :enabled_day, :expiration_day
belongs_to :employee
belongs_to :branch
def self.default_scope
where '? BETWEEN enabled_day AND expiration_day', Date.current
end
end

Many to many relationship with metadata stored in the mapping table in activerecord

I have two tables with a many to many relationship, through a third table. In the third table is a piece of data I need to assign when I build the relationships between the two tables, how can I use ActiveRecords build method to assign that?
Here is code to show what I mean:
class Company < Contact
has_many :contact_companies
has_many :people, :through => :contact_companies
accepts_nested_attributes_for :people, :allow_destroy => true
accepts_nested_attributes_for :contact_companies
end
class Person < Contact
has_many :contact_companies
has_many :companies, :through => :contact_companies
accepts_nested_attributes_for :companies, :allow_destroy => true
accepts_nested_attributes_for :contact_companies
end
class ContactCompany < ActiveRecord::Base
belongs_to :person
belongs_to :company
end
ContactCompany contains a data member called "position". What I want to do is something like:
c = Person.new
c.companies.build(:name => Faker::Company.name, :position => positions.sample)
EDIT:
When I try the code above I get "unknown attribute: position".
The c.companies.build line is attempting to build a Company object which does not have the position attribute (the ContactCompany does) hence the error. It looks like you are trying to set attributes on two different models, so you'll have to make sure you are setting the appropriate attribute on the right model:
# you can chain these calls but I separated them for readability
cc = c.contact_companies.build(:position => positions.sample)
cc.build_company(:name => Faker::Company.name)

Rails 3 - Nested Form and has_many through association

Hi people, long time not been here. But I'm back because I need your help again please. I have a rails 3.0.9 app, and I'm working with nested forms and has_many through association. When i create an instance, it works great. The problems come when I try to edit. Here is an example for a better explanation. (table names and attributes are just for explaining)
Table Client
id
company_name
address
Table Worker
id
first_name
last name
Table Contact
id
client_id
worker_id
my models looks like these
class Worker < ActiveRecord::Base
has_many :contacts, :dependent => :destroy
has_many :clients, :through => :contacts, :foreign_key => 'client_id'
end
class Client < ActiveRecord::Base
has_many :contacts, :foreign_key => "client_id",:dependent => :destroy
has_many :workers, :through => :contacts, :foreign_key => 'worker_id'
accepts_nested_attributes_for :workers, :allow_destroy => false
end
class Contact < ActiveRecord::Base
belongs_to :worker, :foreign_key => "worker_id"
belongs_to :client, :foreign_key => "client_id"
end
Then in my form for create a client, I can create many workers, and rails make the association and creates the instances for the contacts table (by using nested forms).
The thing is, if I want to edit a client by removing a contact, the contact is not removed. As you can see I put this line in the clients model
accepts_nested_attributes_for :workers, :allow_destroy => false
I set the allow_destroy to false, because I don't want to delete the worker itself, I just want to remove the contact tuple.
Does anybody know how can I solve this?? Hope you can help me... Thanks

Rails has_many :through with custom foreign_key

I have the following set of models:
class Cardstock < ActiveRecord::Base
has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
has_many :palette_colors, :through => :color_matches
end
class ColorMatch < ActiveRecord::Base
belongs_to :palette_color
has_many :cardstocks, :foreign_key => :hex, :primary_key => :hex
end
class PaletteColor < ActiveRecord::Base
has_many :color_matches
has_many :cardstocks, :through => :color_matches
end
Calling Cardstock.last.palette_colors yields the following error:
ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: character varying = integer
LINE 1: ...".palette_color_id WHERE (("color_matches".hex = 66)) OR...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "palette_colors".* FROM "palette_colors" INNER JOIN "color_matches" ON "palette_colors".id = "color_matches".palette_color_id WHERE (("color_matches".hex = 66)) ORDER BY name ASC
This shows me that the query ActiveRecord generates is using the cardstock's id (66) where it should be using the cardstock's hex (bbbbaf). Somewhere, I need to specify to ActiveRecord to use the hex column to join between cardstocks and color_matches. Does ActiveRecord support this?
Your relationships are all out of whack here.
the relationships between Cardstock and ColorMatch should be a has_and_belongs_to_many relationship on both sides
anywhere you have a has_many relationship, you need a corresponding belongs_to relationship in the corresponding class
There's something wrong with the way your relationships are set up. I don't quite understand your specific use case here, so I'm not sure where the problem is. The way to think about this is probably as a many-to-many relationship. Figure out what the two sides of that many-to-many are, and what's the join model. I'm going to give an example assuming that ColorMatch is your join model -- it's what relates a PaletteColor to a Cardstock. In that case, you'll want your relationships to look something like this:
class Cardstock < ActiveRecord::Base
has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
has_many :palette_colors, :through => :color_matches
end
class ColorMatch < ActiveRecord::Base
belongs_to :palette_color
belongs_to :cardstocks, :foreign_key => :hex, :primary_key => :hex
end
class PaletteColor < ActiveRecord::Base
has_many :color_matches
has_many :cardstocks, :through => :color_matches
end
In terms of your database, you should have a palette_color_id and a hex field on the color_matches table, and a hex field on the cardstocks table.