I am trying to extract all Posts for a given User in the bellow relationships. Not sure whether I got them right, so I'll better explain. A User has Ownerships and Memberships in some Groups. A User can be either a Member or an Owner of the Group, but not both. Every Post has an id of the user and of the group. I think the problem is due to the relationships noted below. How can I get around it? One more thing. I have to also find all posts that were posted by other users in the user's groups. In other words, I have to pass through groups.
/-- Owner ---\
User -- -- Group -- Post
| \-- Member --/ |
|_______________________________|
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :ownerships, :foreign_key => "user_id", :dependent => :destroy
has_many :memberships, :foreign_key => "user_id", :dependent => :destroy
# Problem with these two? I think so.
has_many :groups, :through => :memberships, :source => :user
has_many :groups, :through => :ownerships, :source => :user
class Ownership < ActiveRecord::Base
belongs_to :users, :class_name => "User"
belongs_to :groups, :class_name => "Group"
has_many :posts, :through => :groups, :source => :posts
class Membership < ActiveRecord::Base
belongs_to :users, :class_name => "User"
belongs_to :groups, :class_name => "Group"
has_many :posts, :through => :groups, :source => :posts
class Group < ActiveRecord::Base
has_many :posts, :dependent => :destroy
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :groups
The errors is coming from the line:
_groups = user.groups
The error as following:
Could not find the source association(s) :user in model Ownership. Try 'has_many :groups, :through => :ownerships, :source => '. Is it one of :users, :groups, or :postings?
First up: you're getting that error you're seeing because you've defined the associations in the Membership and Ownership table as this:
belongs_to :users
When they should belong to only one user, i.e. singular user:
belongs_to :user
But even then you will run into problems!
I think having a Membership model and an Ownership model are what will trip you up next. I don't understand what the purpose of having an Ownership model provides, other than signifying ownership of a group, which could be done by a field on the memberships table's records called owner for instance. It's over-engineering.
The problem with the Rails code you've got there is that you're defining that you have many posts through one association and then you're telling it that you have many posts through another association. In effect, you're doing this:
def posts
# find posts for the groups that I own
end
def posts
# find posts for the groups I belong to
end
It is not mistake here that there are two identically-named methods. This is exactly what you are doing by defining two has_many associations with the same name.
So hopefully now you can see why having an Ownership and a Membership model is the path to madness.
I would really recommend that you just have a Membership model that has a boolean attribute declaring an owner for a group. This would also mean that, if you wanted to, you could have new owners for a group in a very easy fashion: just flip the boolean. No need to create another record in another table.
One Membership model to rule them all.
Related
I can't seem to work around the name convention or if I'm joining them incorrectly.
This is the error I'm getting from the user model:
> user.companies
NameError: uninitialized constant User::CompaniesUser
And from the company model:
> company.users
NameError: uninitialized constant Company::CompaniesUser
user.rb
has_many :companies_users
has_many :companies, :through => :companies_users
company.rb
has_many :companies_users
has_many :users, :through => :companies_users
company_user.rb
class CompanyUser < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
I've been looking up through examples but I honestly don't understand why it keeps exploding. If there's any additional information needed, I'll provide it, I appreciate any help given.
Your association companies_users will be mapped to class named CompaniesUser by Rails because "companies_users".classify will give you CompaniesUser. But the class you want to associate is CompanyUser, so the solution in this case would be to modify your associations to include class_name option as follows:
# user.rb
has_many :companies_users, class_name: CompanyUser
has_many :companies, :through => :companies_users
# company.rb
has_many :companies_users, class_name: CompanyUser
has_many :users, :through => :companies_users
Update: This is of course if you want to stick with the association name companies_users, otherwise #Babur has a solution for you.
It should be:
has_many :company_users
has_many :companies, :through => :company_users
Only last word should be pluralized
Because of your has_many :companies_users in your Company model, Rails tried to load a model class for that table, that be convention would be called CompaniesUser. To make your code work, you could either change your has_many declaration to
has_many :company_users
or even get rid of the CompanyUser model completely and use has_and_belongs_to_many instead.
class User
has_and_belongs_to_many :companies
end
class Company
has_and_belongs_to_many :users
end
I am developing some voting software where a user gets to vote for 3 different entries. For the votes model I was thinking of something like:
Votes:
Email Address - String
Verification Code - String
Verified - Boolean
First - Entry
Second - Entry
Third - Entry
Where Entry is another model in my rails application. How could I have a belongs to relationship for this? As i'd like to run queries like get the entries with the highest number of votes for first place. Is this the best approach to this problem?
User Model:
has_many :votes, :dependent => :destroy
has_many :entries, :through => :votes
Entry Model
has_many :votes, :dependent => :destroy
has_many :users, :through => :votes
Vote Model
belongs_to :user
belongs_to :entry
I would design the Vote object such that it contains just a user_id and an entry_id. Then your application logic would enforce that if they've already voted three times, they don't get to vote again. That way, when you query for the highest number of votes, you don't have to write special cases for the first, second and third entries.
As far as the belongs_to declaration, I would say that a vote belongs_to both User and Entry, and should be destroyed when either dependent object is destroyed, thus:
class Vote < ActiveRecord::Base
belongs_to :user, :dependent => :destroy
belongs_to :entry, :dependent => :destroy
end
I have a content model represented by class: content. Now users can rate content, review content or do both. I want to find all the content that a user have either rated, reviewed or rated and reviewed. The reviews table has a many-to-one association with the content table (meaning a content can be reviewed many times). A similar relationship exists between the ratings table and the content table.
I'm thinking I should do separate queries to find all rated content by a user, then all reviewed content by a user, then do a union. But I can't find out how to do a union that returns an active record relation. I need a relation because I want to paginate the results.
Thank you.
Ok, so first let's set up your models. From your explanation I'm thinking you'll want something like this:
class Content < ActiveRecord::Base
has_many :reviews
has_many :reviewing_users, :through => :reviews, :class_name => "User"
has_many :ratings
has_many :rating_users, :through => :ratings, :class_name => "User"
end
class User < ActiveRecord::Base
has_many :reviews
has_many :reviewed_contents, :through => :reviews, :class_name => "Content"
has_many :ratings
has_many :rated_contents, :through => :ratings, :class_name => "Content"
end
class Review < ActiveRecord::Base
belongs_to :content
belongs_to :user
end
class Rating < ActiveRecord::Base
belongs_to :content
belongs_to :user
end
And then for a given user you can find all the content that they've reviewed and/or rated with:
( user.reviewed_contents + user.rated_contents ).uniq
(user.reviewed_contents + user.rated_contents).uniq returns an array, not a relation, so beware. You can test this by attempting to call a class method on #posts (other than paginate).
You can still paginate though. just use #posts.paginate, as the will_paginate gem adds a paginate method to the array class.
In my application I have the following situation:
User belongs_to Group
Group has_many Users
Project belongs_to User
User has_many projects
The following is also true:
- Each Group will have one BaseCase
- Each Project will have multiple Scenarios and one BaseCase(depending on the Group the Project User belongs to)
- Scenario and BaseCase is the same type of object (let's call this Data)
- The default values for each Scenario are the BaseCase values for the Group, but the User can change these default values to create the specific Scenario
I am not sure how to capture all these relationships through associations efficiently, does anyone have any ideas? thanks
If I understand correctly, then something like that
class User
belongs_to :group
has_many :projects
end
class Group
has_many :users
has_many :projects, :through => :users
has_one :base_case
end
class Project
has_many :scenarios
has_one :base_case
belongs_to :user
has_one :group, :through => user
has_one :base_case, :through => :group
end
class Scenario
belongs_to :project
has_one :base_case, :through => :project
before_create do
self.attributes = self.base_case.attributes.except(:group_id, ...)
end
end
class BaseCase
belongs_to :group
end
In Rails 3 with ActiveRecord, I have 2 models (Users and Tasks). These models are linked together with a has_many :through association on another model, Assignments. How can I find all Tasks that are NOT associated to a particular user?
class User < ActiveRecord::Base
has_many :assignments
has_many :tasks, :through => :assignments
end
class Tasks < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
class Assignments < ActiveRecord::Base
belongs_to :users
belongs_to :tasks
end
Short 'n sweet:
Task.all - user.tasks
Avoid loading user tasks:
Task.where('id not in (?)', user.task_ids)
I couldn't figure out how to do it with an outer join in AR.
I'm going to assume you want those tasks without any associated user, rather than not associated to a user in particular.
Tasks.joins('left outer join assignments on assignments.task_id = tasks.id').where('assignments.* is null')