Rails has_many with alias name - ruby-on-rails

In my User model I could have:
has_many :tasks
and in my Task model:
belongs_to :user
Then, supposing the foreign key 'user_id' was stored in the tasks table, I could use:
#user.tasks
My question is, how do I declare the has_many relationship such that I can refer to a User's Tasks as:
#user.jobs
... or ...
#user.foobars
Thanks a heap.

Give this a shot:
has_many :jobs, foreign_key: 'user_id', class_name: 'Task'
Note, that :as is used for polymorphic associations.
Also, foreign_key option for has_many.

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:
class User < ActiveRecord::Base
alias_attribute :jobs, :tasks
has_many :tasks
end

If you use has_many through, and want to alias:
has_many :alias_name, through: :model_name, source: :initial_name
(thanks for the correction Sami Birnbaum)

To complete #SamSaffron's answer :
You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :
class BlogPost
has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post
end
and you need to make sure you have the belongs_to attribute on the child model:
class BlogPostImage
belongs_to :blog_post
end

Related

Rails 4 has_many through naming

I'm having problems with a Rails 4 join table. I have quite a simple setup which is working elsewhere in my application using a non-conventionally named table for users, groups and usergroupmemberships. I'm trying to set it up this time using the proper conventional naming and it's just not working.
Models involved are User, ManagementGroup and ManagementGroupsUser
db tables: management_groups_user, management_groups, users
app/models/user.rb
Class User < ActiveRecord::Base
...
has_many :management_groups, through: management_groups_users
has_many :management_groups_users
....
app/models/management_group.rb
class ManagementGroup < ActiveRecord::Base
has_many :users, through: :management_groups_users
has_many :management_groups_users
app/models/management_groups_user.rb
class ManagementGroupsUser < ActiveRecord::Base
belongs_to :users
belongs_to :management_groups
The association appears to work from with #user.management_groups_users but nothing else. I'm fairly sure this is a problem with naming / plurality but I can't figure it out.
This is the model which joins the remaining models user.rb and management_group
#app/models/management_groups_user.rb
belongs_to :user
belongs_to :management_group
Since we are going to use model above to access another model management_group then
#app/models/user.rb
has_many :user_management_groups #This should come first
has_many :management_groups, through: user_management_groups
Since we are going to use model above to access another user model then
app/models/management_group.rb
has_many :user_management_groups
has_many :users, through: :user_management_groups
Now should work
Do it this way.
app/models/user.rb
has_many :user_management_groups
has_many :management_groups, through: user_management_groups
app/models/management_group.rb
has_many :user_management_groups
has_many :users, through: :user_management_groups
app/models/management_groups_user.rb
belongs_to :user
belongs_to :management_group
I hope these associations will help you.
This is another way if you pass foreign key and class name.
app/models/user.rb
has_many :user_management_groups, :foreign_key => "key", :class_name => "ClassName"
has_many :management_groups, through: user_management_groups, :foreign_key => "key", :class_name => "ClassName"
app/models/management_group.rb
has_many :user_management_groups
has_many :users, through: :user_management_groups
app/models/management_groups_user.rb
belongs_to :user, class_name: "ClassName"
belongs_to :management_group, class_name: "ClassName"
This is another way around.
It's important to realize there is a convention rails uses for HABTM and has many through. HABTM does not have a model, so it needs to infer the table name which, as others point out, is both plural and alphabetical order.
If you are doing has many through and have a model, the convention is that it wants singular first word, plural second. See examples
User has and belongs to many groups.
HABTM: table name should be groups_users
Has Many Through: table name should be user_groups (flip order is more intuitive)
Model for the latter would be UserGroup. Has many through would specify it as through: :user_groups

Rails 4 has_many through many

I'm stuck on this:
class Worker < ActiveRecord::Base
has_many :skills
has_many :jobs, through: :skills
..
end
class Skill < ActiveRecord::Base
belongs_to :worker
has_many :jobs
..
end
class Job < ActiveRecord::Base
has_many :skills
has_many :workers, through: :skills
..
end
What I'm trying to do is set up a many to many between Skill and Job inside of the `has_many' through relationship?
My question has three parts
Is this possible - using the has_many jobs rather than belongs_to jobs.
If it can be done and the code is wrong, how do I fix it?
How can I create Worker, Skill and Job records? (looking for syntax)
This is a picture (of sorts) of what I'm trying to do, hope it helps... :(
You're not giving active record enough information about your relationships. Every :has_many should have a corresponding :belongs_to so that active record knows which table holds the foreign key for each association. Notice that you only have one :belongs_to for three relationships. That smells.
As for fixing the problem, you have at least 2 options:
add :has_and_belongs_to_many associations
use explicit join tables
My preference is for the latter option. Being forced to name join tables often clarifies the nature of a relationship. On the flip side, I've found that :has_and_belongs_to_many is often too implicit and ends up making my designs more obscure.
Explicit join tables
You might setup your relationships like this (untested):
class Assignment < ActiveRecord::Base
belongs_to :worker
belongs_to :job
end
class Qualification < ActiveRecord::Base
belongs_to :worker
belongs_to :skill
end
class Worker < ActiveRecord::Base
has_many :qualifications
has_many :skills, through: :qualifications
has_many :assignments
has_many :jobs, through: :assignments
..
end
class Skill < ActiveRecord::Base
has_many :qualifications
has_many :workers, through: :qualifications
has_many :jobs
..
end
class Job < ActiveRecord::Base
has_many :skills
has_many :workers, through: :assignments
..
end
By making the relationships more explicit I think the model is clearer. It should be easier to troubleshoot from here.
EDIT:
If you need to do a traversal like Job.find(1).qualified_workers try making the following adjustment to the above model:
class Job
has_many :required_competencies
has_many :skills, through: :required_competencies
has_many :qualifications, through: :skills
has_many :qualified_workers, through: qualifications, class_name: :workers
end
class RequiredCompetency
belongs_to :job
belongs_to :skill
end
This is explicit about each traversal and names it. If you find these paths through your system are getting really long, I'd consider that a smell. There might be a more direct way to fetch your data or perhaps a better way to model it.

Rails: How to make has_many :through association work with Single Table Inheritance

So in my current project I have an Article model that can have different kinds of Transactions. It has one main Transaction, but under certain circumstances it can have multiple sub-transactions.
Until now I set it up like this:
class Article < ActiveRecord::Base
has_one :transaction, inverse_of: :article
has_many :partial_transactions, through: :transaction, source_type: 'MultipleFixedPriceTransaction', source: 'PartialFixedPriceTransaction', inverse_of: :articles
end
class Transaction < ActiveRecord::Base
belongs_to :article, inverse_of: :transaction # Gets inherited to all kinds of Transaction subclasses
end
class MultipleFixedPriceTransaction < Transaction
has_many :children, class_name: 'PartialFixedPriceTransaction', foreign_key: 'parent_id', inverse_of: :parent
end
class PartialFixedPriceTransaction < Transaction
belongs_to :parent, class_name: 'MultipleFixedPriceTransaction', inverse_of: :children
belongs_to :article, inverse_of: :partial_transactions # Overwriting inheritance
end
Now with this set up I sometimes get errors like
ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to
source_reflection.foreign_key, but source_reflection is nil:
#<ActiveRecord::Reflection::ThroughReflection:0x00000009bcc3f8 #macro=:has_many,
#name=:partial_transactions, #options={:through=>:transaction,
:source_type=>"MultipleFixedPriceTransaction",
:source=>"PartialFixedPriceTransaction", :inverse_of=>:articles, :extend=>[]},
#active_record=Article(id: integer ...
By the way, I experimented a lot with the source and source_type parameters and the ones there are just examples. I don't really know what to do with them.
So, how can I make this work? How is the association set up correctly?
Thank you.

has_many :through with class_name and foreign_key

I'm working with a fairly straightforward has_many through: situation where I can make the class_name/foreign_key parameters work in one direction but not the other. Perhaps you can help me out. (p.s. I'm using Rails 4 if that makes a diff):
English: A User manages many Listings through ListingManager, and a Listing is managed by many Users through ListingManager. Listing manager has some data fields, not germane to this question, so I edited them out in the below code
Here's the simple part which works:
class User < ActiveRecord::Base
has_many :listing_managers
has_many :listings, through: :listing_managers
end
class Listing < ActiveRecord::Base
has_many :listing_managers
has_many :managers, through: :listing_managers, class_name: "User", foreign_key: "manager_id"
end
class ListingManager < ActiveRecord::Base
belongs_to :listing
belongs_to :manager, class_name:"User"
attr_accessible :listing_id, :manager_id
end
as you can guess from above the ListingManager table looks like:
create_table "listing_managers", force: true do |t|
t.integer "listing_id"
t.integer "manager_id"
end
so the only non-simple here is that ListingManager uses manager_id rather than user_id
Anyway, the above works. I can call user.listings to get the Listings associated with the user, and I can call listing.managers to get the managers associated with the listing.
However (and here's the question), I decided it wasn't terribly meaningful to say user.listings since a user can also "own" rather than "manage" listings, what I really wanted was user.managed_listings so I tweaked user.rb to change
has_many :listings, through: :listing_managers
to
has_many :managed_listings, through: :listing_managers, class_name: "Listing", foreign_key: "listing_id"
This is an exact analogy to the code in listing.rb above, so I thought this should work right off. Instead my rspec test of this barfs by saying
ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source association(s) :managed_listing or :managed_listings in model ListingManager. Try 'has_many :managed_listings, :through => :listing_managers, :source => <name>'. Is it one of :listing or :manager?
the test being:
it "manages many managed_listings" do
user = FactoryGirl.build(:user)
l1 = FactoryGirl.build(:listing)
l2 = FactoryGirl.build(:listing)
user.managed_listings << l1
user.managed_listings << l2
expect( #user.managed_listings.size ).to eq 2
end
Now, I'm convinced I know nothing. Yes, I guess I could do an alias, but I'm bothered that the same technique used in listing.rb doesn't seem to work in user.rb. Can you help explain?
UPDATE:
I updated the code to reflect #gregates suggestions, but I'm still running into a problem: I wrote an additional test which fails (and confirmed by "hand"-tesing in the Rails console). When one writes a test like this:
it "manages many managed_listings" do
l1 = FactoryGirl.create(:listing)
#user = User.last
ListingManager.destroy_all
#before_count = ListingManager.count
expect( #before_count ).to eq 0
lm = FactoryGirl.create(:listing_manager, manager_id: #user.id, listing_id: l1.id)
expect( #user.managed_listings.count ).to eq 1
end
The above fails. Rails generates the error PG::UndefinedColumn: ERROR: column listing_managers.user_id does not exist (It should be looking for 'listing_managers.manager_id'). So I think there's still an error on the User side of the association. In user.rb's has_many :managed_listings, through: :listing_managers, source: :listing, how does User know to use manager_id to get to its Listing(s) ?
The issue here is that in
has_many :managers, through: :listing_managers
ActiveRecord can infer that the name of the association on the join model (:listing_managers) because it has the same name as the has_many :through association you're defining. That is, both listings and listing_mangers have many managers.
But that's not the case in your other association. There, a listing_manager has_many :listings, but a user has_many :managed_listings. So ActiveRecord is unable to infer the name of the association on ListingManager that it should use.
This is what the :source option is for (see http://guides.rubyonrails.org/association_basics.html#has-many-association-reference). So the correct declaration would be:
has_many :managed_listings, through: :listing_managers, source: :listing
(p.s. you don't actually need the :foreign_key or :class_name options on the other has_many :through. You'd use those to define direct associations, and then all you need on a has_many :through is to point to the correct association on the :through model.)
I know this is an old question, but I just spent some time running into the same errors and finally figured it out. This is what I did:
class User < ActiveRecord::Base
has_many :listing_managers
has_many :managed_listings, through: :listing_managers, source: :listing
end
class Listing < ActiveRecord::Base
has_many :listing_managers
has_many :managers, through: :listing_managers, source: :user
end
class ListingManager < ActiveRecord::Base
belongs_to :listing
belongs_to :user
end
This is what the ListingManager join table looks like:
create_table :listing_managers do |t|
t.integer :listing_id
t.integer :user_id
end
Hope this helps future searchers.
i had several issues with my models, had to add the foreign key as well as the source and class name... this was the only workaround i found:
has_many :ticket_purchase_details, foreign_key: :ticket_purchase_id, source: :ticket_purchase_details, class_name: 'TicketPurchaseDetail'
has_many :details, through: :ticket_purchase_details, source: :ticket_purchase, class_name: 'TicketPurchaseDetail'

getting data from a join table

I have self referential model called Profile that is connected through the Relationship model.
class Profile < ActiveRecord::Base
belongs_to :user
has_many :accepted_relationships, class_name: 'Relationship', foreign_key: 'responder_id'
has_many :followers, through: :accepted_relationships, source: 'initiator'
has_many :initiated_relationships, class_name: 'Relationship', foreign_key: 'initiator_id'
has_many :followed_profiles, through: :initiated_relationships, source: 'responder'
has_many :groups
end
class Relationship < ActiveRecord::Base
belongs_to :responder, class_name: 'Profile', foreign_key: 'responder_id'
belongs_to :initiator, class_name: 'Profile', foreign_key: 'initiator_id'
belongs_to :group
end
class Group < ActiveRecord::Base
belongs_to :profile
has_many :relationships
attr_accessible :name
end
The problem is I don't know how to access data on the join model. If I do something like;
user.profiles[1].followers[1]
it will give me the profile I want. I would also like to have something like;
user.profiles[1].followers[1].assigned_group
so I could access the group that the relationship belongs to.
Is my design off, or am I overlooking something here?
I guess, Your Group will have many profiles and does your group require relationships, you can have either relationships or profiles in your group or profiles through relationships
I'm getting closer to an answer. I am passing a block to has_many
has_many accepted_relationships... do
def assigned_group
#code
end
end
I still haven't quite gotten it, but I think this is the route I need to take.

Resources