开发者

:include searches with the wrong value

开发者 https://www.devze.com 2023-04-04 11:35 出处:网络
I have a number of models in a Rails project that are linked to a user, and I\'m running into a loading problem I try to get all of the user\'s data displayed on a page.

I have a number of models in a Rails project that are linked to a user, and I'm running into a loading problem I try to get all of the user's data displayed on a page.

My model declarations look sort of like this:

class User < ActiveRecord::Base
  validates_presence_of :server_user_id
  has_many :setup_notes, :foreign_key => "server_user_id"
  has_many :closure_votes, :foreign_key => "user_id"
end

class SetupNote < ActiveRecord::Base
  belongs_to :user, :foreign_key => "server_user_id"
end

I should note that in the SQL table for closure votes, user_id is the same value as server_user_id in the table for users.

When I try using the :include symbol in a Rails query, it ends up using user.id for the search value when I need to find closure votes and setup notes through user.server_user_id. In other words,

me = User.first(:conditions => ["serve开发者_JAVA百科r_user_id = ?", 12610], :include => :setup_notes)

generates the MySQL query

SELECT `setup_notes`.* FROM `setup_notes` WHERE (`setup_notes`.server_user_id = 1)

Which returns an empty set. Is there any way to format the Rails query/models to send the relevant SQL query, or do I need to write a raw query for all of the models associated with the users (and if that's the case, how do I do that?)

Thanks!


If I understand correctly (that User has a server_user_id field), in the User model you have to set the :primary_key option like so:

class User < ActiveRecord::Base
  validates_presence_of :server_user_id
  has_many :setup_notes, :foreign_key => "server_user_id", :primary_key => "server_user_id"
  has_many :closure_votes, :foreign_key => "user_id", :primary_key => "server_user_id"
end
0

精彩评论

暂无评论...
验证码 换一张
取 消