I have a Rails application that I'm in the process of designing. I have a separate model that needs to link to only 2 of one model. Specifically, my "evaluation"s have 2 "member"s, an evaluator, and an evaluatee. They also have a few other pieces of information, too but they should not be relevant to this.
What is the best way to represent this? Would 2 foreign keys in the evaluation be best, or a many-many relationship between the evaluations and the members? Would there be some other option that would work even better?
I would initially think many to many, but since there is a defined number on one side of the relationship I question the applicability here. To my knowledge, many-to-many generally implies that the number on each side of the relation is variable.
You probably want two different associations, possibly with the same class:
class Member < ActiveRecord::Base
has_many :evaluations_out, :class_name => 'evaluation', :as => :evaluator
has_many :evaluations_in, :class_name => 'evaluation', :as => :evaluatee
end
class Evaluation < ActiveRecord::Base
belongs_to :evaluator, :class_name => 'member'
belongs_to :evaluatee, :class_name => 'member'
end
I haven't tested it myself and it might sound a little adventurous, but I think that could work:
Evaluation Model
class Evaluation < ActiveRecord::Base
belongs_to :evaluator, :class_name => "Member", :foreign_key => "evaluator_id"
belongs_to :evaluatee, :class_name => "Member", :foreign_key => "evaluatee_id"
end
Member Model
class Member < ActiveRecord::Base
has_many :evaluators, :class_name => "Evaluation", :foreign_key => "evaluator_id"
has_many :evaluatees, :class_name => "Evaluation", :foreign_key => "evaluatee_id"
end
Related
Here is what I'm trying to do:
class Cashflow < ActiveRecord::Base
belongs_to from_account, :class_name => 'Account'
belongs_to to_account, :class_name => 'Account'
end
class Account < ActiveRecord::Base
has_many :cashflows
end
where Account::cashflows is obviously a list of all cashflows that either have the account_id stored in from_account or in to_account.
I'm confused. What is the proper way of handling such a case? How bad design is this? What would be the proper way of designing such a relation?
I think you have the right structure as there can only two accounts be involved in a particular transaction/cashflow. if you use many to many association you would need to handle the validation for not involving more or less than 2 accounts. For your current structure you can change your moidel associations to be:
class Cashflow < ActiveRecord::Base
belongs_to from_account, :class_name => 'Account', :foreign_key => :from_account
belongs_to to_account, :class_name => 'Account', :foreign_key => :to_account
end
class Account < ActiveRecord::Base
has_many :debits, :class_name => 'Cashflow', :foreign_key => :from_account
has_many :credits, :class_name => 'Cashflow', :foreign_key => :to_account
def cashflows
transactions = []
transactions << self.debits
transactions << self.credits
transactions.flatten!
## or may be the following commented way
# Cashflow.where('from_account = ? OR to_account = ?', self.id, self.id)
end
end
This way you can keep track of the amount debited/credited in a particular account and also get the accounts involved in a particular transaction/cashflow.
Suggestions on top of my mind
1) Your class (table) cashflows should have two columns from_account and to_account.
2) from_account and to_account should have the id of the account concerned
3) cashflows should belongs_to :account
4) account should has_many :cashflows. Ideally it should be cash_flows
These should be good starting points. Don't they meet your requirements?
I think you should use has and belongs to many association here:
class Account < ActiveRecord::Base
has_and_belongs_to_many :incoming_cashflows, :class_name => 'Cashflow', :join_table => :incoming_cashflows_accounts
has_and_belongs_to_many :outcoming_cashflows, :class_name => 'Cashflow', :join_table => :outcoming_cashflows_accounts
end
class Cashflow < ActiveRecord::Base
has_and_belongs_to_many :from_accounts, :class_name => 'Account', :join_table => :incoming_cashflows_accounts
has_and_belongs_to_many :to_accounts, :class_name => 'Account', :join_table => :outcoming_cashflows_accounts
end
Also you will need some validation code allows to add only one account to Cashflow.
I have Flight, Person, and Glider models in a Rails 3 app. I've defined custom relationships because I need more than one foreign key referencing a Person from the flights table. Associations work but ONE-WAY only.
class Flight < ActiveRecord::Base
belongs_to :pilot, :class_name => "Person"
belongs_to :instructor, :class_name => "Person"
belongs_to :towplane_pilot, :class_name => "Person"
belongs_to :airplane_instructor, :class_name => "Person"
belongs_to :glider
belongs_to :rep_glider, :class_name => "Glider"
belongs_to :departure_airfield, :class_name => "Airfield"
belongs_to :arrival_airfield, :class_name => "Airfield"
end
class Glider < Aircraft
has_many :flights
has_many :replaced_flights, :foreign_key => "rep_glider_id", :class_name => "Flight"
end
class Person < ActiveRecord::Base
has_many :flights, :foreign_key => "pilot_id", :class_name => "Flight"
has_many :instructed_flights, :foreign_key => "instructor_id", :class_name => "Flight"
has_many :towed_flights, :foreign_key => "towplane_pilot_id", :class_name => "Flight"
has_many :instructed_towing_flights, :foreign_key => "airplane_instructor_id", :class_name => "Flight"
end
####What works#####
Flight.first.glider
Flight.first.rep_glider
Flight.first.pilot
Flight.first.instructor
Flight.first.towplane_pilot
Flight.first.airplane_instructor
Glider.first.flights
Glider.first.replaced_flights
####What doesn't work#### ----> NoMEthodError 'match'
Person.first.flights
Person.first.instructed_flights
Person.first.towed_flights.
Person.first.instructed_towing_flights
I'm almost there, but I don't understand how Glider.first.flights does work when Person.first.flights doesn't.
UPDATE: Associations with 'Airfield' works... so I'm clueless as to why it doesn't work with 'Person'
class Airfield < ActiveRecord::Base
has_many :takeoff_flights, :foreign_key => "departure_airfield_id", :class_name => "Flight"
has_many :grounded_flights, :foreign_key => "arrival_airfield_id", :class_name => "Flight"
end
###Works Correctly
Airfield.first.takeoff_flights
Airfield.first.grounded_flights
Flight.first.departure_airfield
Flight.first.arrival_airfield
Do your pilots have types? like a pilot_type column? I just also started reading into these kinds of patterns and luckily it's still a bit fresh(hopefully. please correct me if Im wron rails ninjas! :))
You are in need of the polymorphic pattern as discussed here:
http://asciicasts.com/episodes/154-polymorphic-association
I've been told that the association between these models is set correctly.
I added a new record to the flights table, and now the associations work correctly with this new record and all the previous ones. I'm not really sure how it is working now, but it sure does.
I have multiple models with created_by and modified_by columns. This is what I have for a Deal Model.
class Deal
has_one :user , :foreign_key => 'created_by'
has_one :user , :foreign_key => 'modified_by'
end
class User
belongs_to :created_by , :class_name => 'Deal' , :foreign_key => 'created_by'
belongs_to :modified_by , :class_name => 'Deal' , :foreign_key => 'modified_by'
end
When I create the deal, looks like it is saving correctly. But in the show view when I try to get #deal.created_by.email I get an "undefined method email" error. Can some tell me how to get this working please?
Also since I have multiple models with these two columns, there can be many belongs_to in User model. Is there an elegant solution for this case?
First thing you have to add is the specification of accessible attributes.
In User you would have to add:
attr_accessible :email, :created_by, :modified_by
In Deal:
attr_accessible :created_by, :modified_by
But you should also change the direction of your relation. The foreign_key is always on the belongs_to side.
This is what worked for me:
class Deal < ActiveRecord::Base
belongs_to :created_by, :class_name => "User", :foreign_key => "created_by"
belongs_to :modified_by, :class_name => "User", :foreign_key =>"modified_by"
attr_accessible :created_by, :modified_by, :name
end
class User < ActiveRecord::Base
has_many :created_deals, :class_name => "Deal", :foreign_key => "created_by"
has_many :modified_deals, :class_name => "Deal", :foreign_key => "modified_by"
attr_accessible :created_deals, :modified_deals, :name
end
If you have more models, which look similiar you could probably use polymorphic associations: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
First of all, from my experience it is generally a bad idea to have associations using the foreign key as name. Especially when writing fixtures it seems rails will get confused between setting the actual value "created_by" or the model in the created_by association. In my models I generally use these associations for the cases you describe:
belongs_to :creator, :class_name => "User", :foreign_key => 'created_by'
belongs_to :modifier, :class_name => "User", :foreign_key => 'modified_by'
You can use association names like 'creating_user' instead if you prefer. If you really want created_by as association name you should have created_by_id or something similar as foreign key, just as long as its not equal to the association name.
Then I am a bit confused by your pasted code. Your choice "Deal has_one User" and "User belongs_to Deal" means that the users table will have the columns created_by and modified_by (foreign keys) containing Deal Ids, basically meaning that users get created by a single deal? However it seems like deals should get created by users and not the other way round. Your example of deal.created_by.email can not work at all with your associations, since deal would not have an association called "created_by", only "user", of which you have two associations with the same name in a single model which can not work at all in the first place.
Fixing your associations similar to what Patrick suggested:
class Deal < ActiveRecord::Base
belongs_to :creator, :class_name => "User", :foreign_key => "created_by"
belongs_to :modifier, :class_name => "User", :foreign_key =>"modified_by"
end
class User < ActiveRecord::Base
has_many :created_deals, :class_name => "Deal", :foreign_key => "created_by"
has_many :modified_deals, :class_name => "Deal", :foreign_key => "modified_by"
end
I have a model, Couple, which has two columns, first_person_id and second_person_id and another model, Person, whose primary key is person_id and has the column name
Here's the usage I want:
#including 'Person' model for eager loading, this is crucial for me
c = Couple.find(:all, :include => :persons)[0]
puts "#{c.first_person.name} and #{c.second_person.name}"
So how can I do this?
The relationships declared in Couple should look like this:
class Couple
named_scope :with_people, { :include => [:first_person, :second_person] }
belongs_to :first_person, :class_name => 'Person'
belongs_to :second_person, :class_name => 'Person'
end
#usage:
Couple.with_people.first
# => <Couple ... #first_person: <Person ...>, #second_person: <Person ...>>
Those in Person depend on whether a Person can be part of more than one Couple. If a Person can only belong to one Couple and can't be the "first" Person on one and the Second on another, you might want:
class Person
has_one :couple_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_one :couple_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couple
couple_as_first_person || couple_as_second_person
end
end
If a Person can belong to several Couples, and there's no way to tell whether they're the "first" or "second" in any given Couple, you might want:
class Person
has_many :couples_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_many :couples_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couples
couples_as_first_person + couples_as_second_person
end
end
Untested, but according to the Rails API documentation, maybe something like:
class Couple < ActiveRecord::Base
has_one :person, :foreign_key => :first_person_id
has_one :person, :foreign_key => :second_person_id
end
Theory only, untested:
Create two subclasses of Person:
class FirstPerson < Person
belongs_to :couple
class SecondPerson < Person
belongs_to :couple
Couple class has_many of each:
class Couple
has_many :first_persons, :foreign_key => :first_person_id
has_many :second_persons, :foreign_key => :second_person_id
Then find:
Couple.all(:include => [:first_persons, :second_persons])
I run the risk of palm-to-forehead here, but I can't quite figure out how to do this with Rails' ActiveRecord sugar.
I have a tickets table that has two columns (submitter_id and assignee_id) that should each reference a different user from the users table (specifically the id column in the users table). I'd like to be able to do things like ticket.submitter.name and ticket.assignee.email using ActiveRecord's associations. Submitter and Assignee are simply user objects under different associative names.
The only thing I've found that comes close to what I am doing is using polymorphic associations, but in the end I'm fairly certain that it's not really what I need. I'm not going to have multiple types, both submitter and assignee will be users, and very well could be two different users.
Any help would be fantastic. Thanks!
class Ticket < ActiveRecord::Base
belongs_to :submitter, :class_name => "User"
belongs_to :assignee, :class_name => "User"
end
Should work.
Edit: Without trying it out, I'm not sure whether you need the :foreign_key parameter or not. My instinct is not, but it couldn't hurt.
Edit again: Sorry, left off the User -> Ticket associations. You didn't mention using them, and I typically will only add associations in one direction if I don't plan on using them in the other direction.
Anyway, try:
class User < ActiveRecord::Base
has_many :assigned_tickets, :class_name => "Ticket", :foreign_key => "assignee_id"
has_many :submitted_tickets, :class_name => "Ticket", :foreign_key => "submitter_id"
end
Something like this should work
class Ticket < ActiveRecord::Base
belongs_to :submitter, :class_name => 'User', :foreign_key => 'submitter_id'
belongs_to :assignee, :class_name => 'User', :foreign_key => 'assignee_id'
end
class User < ActiveRecord::Base
has_many :tickets, :class_name => 'Ticket', :foreign_key => 'submitter_id'
has_many :tickets_assigned, :class_name => 'Ticket', :foreign_key => 'assignee_id'
end
Yes, PreciousBodilyFluids is right we don't need to specify the foreign_key in the Ticket class as rails can infer it from the column name, i.e. submitter_id and assignee_id
But if your association name is different from the column_name_{id} then you will have to specify it, i.e. the User class case