rails 3.1 - has_one, through - ruby-on-rails-3

Is it possible to make a has_one relationship work like this?
I would like to be able able to load records like this:
#person = Person.find(1) => {Person id: 1, favorite_house_id: 10}
#person.favorite_house => {House id: 10....)
class Person < ActiveRecord::Base
has_many :houses, through: :person_houses
has_one :favorite_house, through: :person_houses
end
class PersonHouse < ActiveRecord::Base
belongs_to :house
belongs_to :person
end
class House < ActiveRecord::Base
has_many :people, through: :person_houses
end

Replace the has_one relation of Person by:
belongs_to :favorite_house, :class_name => "House"
Do not forget to create a column favorite_house_id in the table of Person.

Related

Rails ActiveRecord query on existing collection

Suppose I have a result from a query:
allCourses = Course.all
Then I also have another set:
myCourses = current_user.courses.all
How can I get a set of items that are in allCourses and NOT in myCourses?
Here are the models:
class Student < ActiveRecord::Base
has_many :student_enrollments, dependent: :destroy
has_many :courses, through: :student_enrollments
end
class Course < ActiveRecord::Base
has_many :student_enrollments, dependent: :destroy
has_many :students, through: :student_enrollments
end
class StudentEnrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
I can always write raw SQL script to achieve the result, but I prefer to find a Rails way to do it.
Thanks
Assume your fk is user_id.
ohterCourses = Course.where('user_id != ?', current_user.id)

Using has_many through with nested namespaces

I have a nested model like so:
class Games::Player < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :games_extras_achievements_players, :class_name => 'Games::Extras::AchievementsPlayer'
has_many :games_extras_achievements, :class_name => 'Games::Extras::Achievement',:through=>:games_extras_achievements_players
validates :user_id,uniqueness: true
end
class Games::Extras::Achievement < ActiveRecord::Base
has_many :games_extras_achievements_players, :class_name => 'Games::Extras::AchievementsPlayer'
has_many :games_players, through: :games_extras_achievements_players, class_name: 'Games::Player'
end
class Games::Extras::AchievementsPlayer < ActiveRecord::Base
attr_accessible :games_extras_achievement_id, :games_player_id
belongs_to :games_extras_achievement, :class_name => 'Games::Extras::Achievement'
belongs_to :games_player, :class_name => 'Games::Player'
end
Objects on the join class work as expected.
However trying to get player -> achievement or vice versa gives an error:
> p.games_extras_achievements
Games::Extras::Achievement Load (0.3ms) SELECT "games_extras_achievements".* FROM "games_extras_achievements" INNER JOIN "games_extras_achievements_players" ON "games_extras_achievements"."id" = "games_extras_achievements_players"."games_extras_achievement_id" WHERE "games_extras_achievements_players"."player_id" = 1
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column games_extras_achievements_players.player_id does not exist
LINE 1: ...ents_players"."games_extras_achievement_id" WHERE "games_ext...
If I change the migration to use player_id like it is trying to find, I get an error stating that games_player_id does not exist
I seem to have fixed it.
I needed to use the non-namespaced column names and add a foreign key constraint.
class Games::Player < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :games_extras_achievements_players, :class_name => 'Games::Extras::AchievementsPlayer'
has_many :games_extras_achievements, :class_name => 'Games::Extras::Achievement',:through=>:games_extras_achievements_players
validates :user_id,uniqueness: true
end
class Games::Extras::Achievement < ActiveRecord::Base
has_many :games_extras_achievements_players, :class_name => 'Games::Extras::AchievementsPlayer'
has_many :games_players, through: :games_extras_achievements_players, class_name: 'Games::Player'
end
class Games::Extras::AchievementsPlayer < ActiveRecord::Base
attr_accessible :achievement_id, :player_id
belongs_to :games_extras_achievement, class_name:'Games::Extras::Achievement',foreign_key: :achievement_id
belongs_to :games_player, class_name: 'Games::Player',foreign_key: :player_id
end
Hopefully this will save someone some aggravation.

Excluding results in has_many :through relation in Rails 3

I am trying to select groups which the #current_user is NOT a member of
The relevant parts of my models are as follows:
class Group < ActiveRecord::Base
belongs_to :user
has_many :group_memberships
has_many :members, :class_name => "User", :through=>:group_memberships
...
class User < ActiveRecord::Base
has_many :group_memberships, :foreign_key => 'member_id'
has_many :groups, :through => :group_memberships
...
class GroupMembership < ActiveRecord::Base
belongs_to :member, :class_name=>"User"
belongs_to :group
end
Thanks!
You could try and do something like:
#groups = Group.where("id NOT IN (?)", current_user.groups)
More information can be found in the Active Record Query.
have a method like this:
def group_ids_not_a_member_of
# get all group_ids and subtract out the ids that he is a member of
Group.pluck('id') - current_user.groups.map(&:id)
end
then
user.group_ids_not_a_member_of

Rails: Find with join model - How to?

I have the following models associations which I want to use in order to do some searches of players:
class Player < ActiveRecord::Base
belongs_to :user
has_many :abilities
has_many :sports, :through => :abilities
...
end
class User < ActiveRecord::Base
has_one :player
...
end
class Ability < ActiveRecord::Base
belongs_to :player
belongs_to :sport
has_one :level
...
end
class Sport < ActiveRecord::Base
has_and_belongs_to_many :category_sports
has_many :abilities
has_many :players, :through => :abilities
...
end
class CategorySport < ActiveRecord::Base
has_and_belongs_to_many :sports
end
I have a form where a user can fill two inputs: city and sport
The city field is in the User model as (#user.city) and the sport field can be either in CategorySport as (#category_sport.name) or in the Sport model as (#sport.name).
Right now I have the following to perform the search in the Player model:
def search
self.find(:all,:include => 'user',:conditions => ['users.city LIKE ?', "%#{city}%"])
end
I would like to know how would I add the join model (ability) and related (sport, categorysport) in this query in order to find by sport too. So, not just find for user city but also by sport.
Try this:
def search
self.includes(:user, :abilities => {:sport => :category_sports}).
where(['users.city LIKE ? OR category_sports.name=? OR sports.name=?',
"%#{city}%", sport, sport])
end

Has_many, through association

Warning:Total Rails Newb (TRN). This should be a pretty basic question so I'm hoping someone can spare a couple mins to help shed some light.
Let's say I have the following models: User, Group, and Member
A user can have many groups (let's say friends, family, etc)
A group can have many members, namely other users.
How would I structure this?
Initially I tried this:
class User < ActiveRecord::Base
has_many :groups
has_many :groups, :through => :members
end
class Groups < ActiveRecord::Base
has_many :users, :through => :members
belongs_to :user
end
class Member < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
However this gave me an error in User so I changed
has_many :groups, :through => :members
to
has_many :memberships, :through => :members, :source => :groups
Still getting an error about missing association when I try to do
group = Group.new
group.user.new
It will be useful: http://railscasts.com/episodes/47-two-many-to-many
class User < ActiveRecord::Base
has_many :members
has_many :groups, :through => :members
has_many :groups_as_owner, :class_name => "Group"
end
class Groups < ActiveRecord::Base
has_many :members
has_many :users, :through => :members
belongs_to :owner, :class_name => "User", :foreign_key => :user_id
end
class Member < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
basically has_many-through associations are n:m associations (join-tables) that (shall) have more attributes than just the id's of the joined record ids...
so you have a table Groups (with an id), a table Users (with an id) and a table Members (no id, but user_id and group_id)
basically, what you did is nearly correct, just think about how you access a group from a user or vice versa....
a user would first look up its member information and through that member information get access to the group information ... and vice versa for a group
so you first set up
has_many :members
and then call
has_many :groups, :through => :members
all you need is
class User < ActiveRecord::Base
has_many :members
has_many :groups, :through => :members
end
class Groups < ActiveRecord::Base
has_many :members
has_many :users, :through => :members
end
class Member < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
and you have another bug in your code above
you might want to use
user = group.users.new
instead of
user = group.user.new
Try this structure:
class User < ActiveRecord::Base
has_many :members
has_many :groups, :through => :members
end
class Groups < ActiveRecord::Base
has_many :members
has_many :users, :through => :members
end
class Member < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
Also take a look at has_and_belongs_to_many, if you don't need to do with class Member then you should use has_and_belongs_to_many. In this case don't forget to create joining table in the database