Hi all,
I'm having problems with the following relationship, can anybody help me out here? I'm using Rails 2.1.
Cheers, Sazima
# Table name: votes
Hi all,
I'm having problems with the following relationship, can anybody help me out here? I'm using Rails 2.1.
Cheers, Sazima
# Table name: votes
Hi all,
I'm having problems with the following relationship, can anybody help me out here? I'm using Rails 2.1.
You don't say exactly what problems you're having, so just some quick comments.
Cheers, Sazima
# Table name: votes # # Field Type Null Default # id int(11) No auto_increment # voter_id int(11) No # voted_id int(11) No # type int(11) No 0 # value varchar(255) Yes NULL # status int(11) Yes 0 # created_at datetime Yes NULL # updated_at datetime Yes NULL #
class Vote < ActiveRecord::Base belongs_to :voter, :class_name => :user, :foreign_key => :voter_id belongs_to :voted, :class_name => :user, :foreign_key => :voted_id end
Can't remember off the top of my head whether it really matters but that should have :class_name => 'User'. You don't need the foreign key option here - the default is assocation name + _id
Your type column will cause problems: rails uses the type column for single table inheritance, as it is you'll probably get some horrendous error whenever you try and load an instance of Vote.
# ------------------------------------------------------------------------------------------------------------
# Table name: users # # id :integer(11) not null, primary key # login :string(255) # crypted_password :string(40) # salt :string(40) # created_at :datetime # updated_at :datetime
class User < ActiveRecord::Base
# Votes has_many :votes_made, :class_name => :vote, :foreign_key => :voter_id has_many :votes_received, :class_name => :vote, :foreign_key => :voted_id
That should probably also be :class_name => 'Vote'
has_many :votees, :through => :votes_made, :source => :user, :uniq => true has_many :voters, :through => :votes_received, :source => :user, :uniq => true
You're not using the :source option correctly. What you're telling rails is 'so load the votes_made association, then grab the association named x (the default would be votee). So you source option here should be :voter or :voted
Fred
Hey Fred,
Thanks a lot for the comments. I had already tried 'User' and 'Vote', as well as commented the "has_many ... through" statements, but didn't thought of the type conflict. That was it! Thanks!
Cheers, Sazima
P.S.: That would be a nice addition to the migration mechanism: an alert when a column with such a name is used...
And yeah, you were also right about the :user x ' User' and :source things...
Cheers, Sazima