has_one :through => multiple - ruby-on-rails

Both Attendment & Vouching:
belongs_to :event
belongs_to :account
Therefore: 1 to 1 relationship between attendments and vouchings.
Is there a way to do this without my thinking too much?
# attendment
has_one :vouching :through => [:event, :account]
Note: I don't mind thinking too much, actually.

Yeah i don't think you can use a has_one for this. Assuming I'm reading this correctly, you have two models:
Attendment
Vouching
They both store an event_id and account_id. You want to know from the attendment model, what vouching shares the same event and account as the attendment. I think the easiest solution for this is to write a method inside your attendment.rb file.
class Attendment < ActiveRecord::Base
# belong to statements go here
def voucher
Voucher.where(:event_id => self.event_id, :account_id => self.account_id).first
end
end

Related

Rails has_many, belongs_to using three tables

I have three tables
Memberships
User_Groupings
Users
This is how I am trying to join them.
User.id == Memberships.user_id
User.user_type == User_Groupings.user_type
Memberships.group_id == User_Groupings.group_id
I would like to do this by using associations if possible.
I have no idea how to do a belongs to or has many that is this complex.
My end goal is to be able to call user_grouping.users and get all users that match the above fields.
visit http://guides.rubyonrails.org/association_basics.html
it will solve all your question related to associations .
User.id == Memberships.user_id
gives:
class Membership
belongs_to :user
class User
has_many :memberships
but the other two are not standard Rails associations.
User.user_type == User_Groupings.user_type
Memberships.group_id == User_Groupings.group_id
You could potentially model these by passing conditions to the associations
perhaps you could update the names of these tow reflect more standard associations (or at least to give us a better idea what you want)
eg
User.user_grouping_id == User_Groupings.id
Memberships.user_grouping_id == User_Groupings.id
then if you want "user_type" you can make it a method eg:
class User
def user_type
self.user_grouping.user_type
end
I may be not quite seeing what you are doing and therefore missing the point.
It seems you are trying to do too much with user_groupings in that it has an ID field fir user_type and group_id. My first reaction would therefore be to say that you should have user_type and group_id to either be in two different tables, or to have them as the same field (the second option seems unlikely)
You have none standard foreign keys by using belongs_to :user, :foreign_key => :xxxxx_id
sorry this isn't directly answering your question, but I think you should take another look at your database design
Looks like you need to have another model to associate memberships and users.
And then you associations will be like this.
class User
belongs_to :user_grouping
has_many :user_memberships, :dependent => :destroy
has_many :memberships, :through => :user_memberships
end
And..
class UserGrouping
has_many :users, :dependent => :nullify
end
And..
class Membership
has_many :user_memberships, :dependent => :destroy
has_many :users, :through => :user_memberships
end
And..
class UserMembership
belongs_to :user
belongs_to :membership
end
Of course, you have to puts respective foreign keys in tables.
Hopefully, this will help you.

How do I sum a many to many value?

Each User can have many Resources, and each of those Resources has many Votes, and each of those votes have a value attribute that I want to sum all that particular users resources.
If I were to type this in a syntactically incorrect way I want something like...
#user.resources.votes.sum(&:value), but that obviously won't work.
I believe I need to use collect but I am not sure?
This is the closest I got but it prints them out, heh
<%= #user.resources.collect { |r| r.votes.sum(&:value) } %>
I'd recommend setting up a has_many :through relationship between the User and Vote objects. Set the models up like this:
class User < ActiveRecord::Base
has_many :resources
has_many :votes, :through => :resources
end
class Resource < ActiveRecord::Base
belongs_to :user
has_many :votes
end
class Vote < ActiveRecord::Base
belongs_to :resource
end
Once this is done you can simply call user.votes and do whatever you want with that collection.
For more info on has_many :through relations, see this guide: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
How can you tell who voted having a Vote instance? Your Vote model has to have voter_id field and additional association:
# in Vote.rb
belongs_to :voter, class_name: 'User', foreign_key: 'voter_id'
And in your User model:
# in User.rb
has_may :submited_votes, class_name: 'Vote', foreign_key: 'voter_id'
So, #user.votes (as David Underwood proposed) will give you #user resources' votes. And #user.submited_votes will give you votes submitted by the #user.
Using just User <- Resource <- Vote relation won't allow you to separate some user's votes made by him and votes made for its resources.
For a total sum this should work or something real close.
sum = 0
#user.resources.each do |r|
r.votes.each do |v|
sum += v.value
end
end
This might work for you:
#user.resources.map {|r| r.votes.sum(:value)}.sum
How many records do you have, there is a way to push this to the database level I believe, I would have to check, but if it is only a few records then doing this in ruby would probably be ok
Try this code
#user.resources.map(&:votes).flatten.map(&:value).sum

Has_many: through in Rails. Can I have two foreign keys?

I am a rails newbie and I am trying to create a database schema that looks like the following:
There are many matches. Each match has 2 teams.
A team has many matches.
The team model and match model are joined together through a competition table.
I have that competition model with a match_id and a team1_id and a team2_id.
But I don't know how to make this work or if it's even the best way to go about it. I don't know how to make certain teams team1 and others team2.... two foreign keys? Is that possible?
The match table also needs to hold additional data like team1_points and team2_points, winner and loser, etc.
You can have as many foreign keys as you want in a table. I wrote an application that involved scheduling teams playing in games.
The way that I handled this in the Game class with the following:
class Game < ActiveRecord::Base
belongs_to :home_team, :class_name => 'Team', :foreign_key => 'team1_id'
belongs_to :visitor_team, :class_name => 'Team', :foreign_key => 'team2_id'
You can add appropriate fields for team1_points, team2_points, etc. You'll need to set up your Team model with something like:
class Team < ActiveRecord::Base
has_many :home_games, :class_name => 'Game', :foreign_key => 'team1_id'
has_many :visitor_games, :class_name => 'Game', :foreign_key => 'team2_id'
def games
home_games + visitor_games
end
#important other logic missing
end
Note that some of my naming conventions were the result of having to work with a legacy database.
I faced a similar problem, and extending the previous answer, what I did was:
class Game < ActiveRecord::Base
def self.played_by(team)
where('team1_id = ? OR team2_id = ?', team.id, team.id)
end
end
class Team < ActiveRecord::Base
def games
#games ||= Game.played_by(self)
end
end
This way, Team#games returns an ActiveRecord::Relation instead of an Array, so you can keep chaining other scopes.

Rails 3: What associations should I use to create model relationships

I am creating an app for uploading and sharing files between users.
I have User and Files models and have created a third File_Sharing_Relationships model which contains a sharer_id, file_id and shared_with_id columns. I want to be able to create the following methods:
#upload.file_sharing_relationships - lists users that the file is shared with
#user.files_shared_with - lists files that are shared with the user.
#user.files_shared - lists files that the user is sharing with others
#user.share_file_with - creates a sharing relationship
Are there any rails associations, such as 'polymorphic' that I could be using to make these relationships?
Any suggestions appreciated. Thanks.
All you need to do is to read Rails Guides and apply all what you learn.
Basically you need to store info about:
user who created a "sharing"
user or group or whatever is a target of a sharing action
resource that is being shared
So:
class SharedItem < ActiveRecord::Base
belongs_to :sharable, :polymorphic => true #this is user, please think of better name than "sharable"...
belongs_to :resource, :polymorphic => true #can be your file
belongs_to :user
end
You need SharedItem to have:
user_id: integer, sharable_id: integer, sharable_type: string, resource_id: integer, resource_type: string
Then you can get "methods" you specified by writing named scopes like:
named_scope :for_user, lambda {|user| {:conditions => {:user_id => user.id} }}
or by specifying proper associations:
class File < ActiveRecord::Base
has_many :shared_items, :as => :resource, :dependent => :destroy
end
I think you should create relationships something like this:
class User
has_many :files
has_many :user_sharings
has_many :sharings, :through => :user_sharings
end
class File
belongs_to :user
end
class Sharing
has_many :user_sharings
has_many :users, :through => :user_sharings
end
class UserSharing
belongs_to :user
belongs_to :sharing
end
.. this is very basic model of relations(It is just my point of view :)). User can have many sharings and also belongs to sharings. You can set file id to UserSharing table when you create user and it's share. And then you can create methods, you listed above, as scopes in proper models. I hope I helped you a little.

Rails + simple role system through associative table

So I have the Ninja model which has many Hovercrafts through ninja_hovercrafts (which stores the ninja_id and the hovercraft_id).
It is of my understanding that this kind of arrangement should be set in a way that the associative table stores only enough information to bind two different classes.
But I'd like to use the associative table to work as a very streamlined authorization hub on my application. So i'd also like this table to inform my system if this binding makes the ninja the pilot or co-pilot of a given hovercraft, through a "role" field in the table.
My questions are:
Is this ugly?
Is this normal?
Are there methods built into rails that would help me to automagically create Ninjas and Hovercrafts associations WITH the role? For exemple, could I have a nested form to create both ninjas and hcs in a way that the role field in ninjas_hovercrafts would be also filled?
If managing my application roles this way isn't a good idea, whats the non-resource heavy alternative (my app is being designed trying to avoid scalability problems such as excessive joins, includes, etc)
thank you
This might not answer you question completely, but if you are only going to have two roles for hovercrafts I would instead set up the associations like this
class Hovercraft < ActiveRecord::Base
belongs_to :pilot, :class_name => 'Ninja', :foreign_key => 'pilot_id'
belongs_to :copilot, :class_name => 'Ninja', :foreign_key => 'copilot_id'
end
class Ninja < ActiveRecord::Base
has_many :pilotings, :class_name => 'Hovercraft', :foreign_key => 'pilot_id'
has_many :copilotings, :class_name => 'Hovercraft', :foreign_key => 'copilot_id'
end
Now if you have more roles than that, or if you need more flexibility you can use a third model to link them together.
class Hovercraft < ActiveRecord::Base
has_many :hovercraft_roles
has_many :ninjas, :through => :hovercraft_roles
end
class HovercraftRole < ActiveRecord::Base
belongs_to :hovercraft
belongs_to :ninja
end
class Ninja < ActiveRecord::Base
has_many :hovercraft_roles
has_many :hovercrafts, :through => :hovercraft_roles
end
With a role attribute in HovercraftRole model to indicated if it is a 'pilot' or 'copilot'.

Resources