开发者

How can I create a join without sql code in rails?

I can't make a join in rails, I don't know what is wrong here. my classes are:

class Serie < ActiveRecord::Base

has_many :user_serie

has_many :user, :through => :user_serie

end

class UserSerie < ActiveRecord::Base

belongs_to :serie

belongs_to :user

end and

class User < ActiveRecord::Base

has_many :user_serie

has_many :serie, :through => :user_serie

end开发者_运维问答

and the select is: @series = Serie.all :joins => :user

so the generated select is:

SELECT "series".* FROM "series" 
INNER JOIN "user_series" ON "series"."id" = "user_series"."serie_id" 
INNER JOIN "users" 
 ON 0 
 AND "users" 
 AND 'id' 
 AND "users"."id" 
 AND 0 
 AND "user_series" 
 AND 'user_id'
 AND "user_series"."user_id" 
 AND "users"."id" = "user_series"."user_id"

What can I do to make this select works?

I've tried to make the has_many with plural, but then I have this error: uninitialized constant Serie::UserSeries


You have wrong relations, should be:

class Serie < ActiveRecord::Base
has_many :user_series
has_many :users, :through => :user_series
end

class UserSerie < ActiveRecord::Base
belongs_to :serie
belongs_to :user
end

class User < ActiveRecord::Base
has_many :user_series
has_many :series, :through => :user_series
end 

When you get exception with uninitialized class, then use explicit :class_name like below:

class Serie < ActiveRecord::Base
has_many :user_series, :class_name => "UserSerie" 
# or "::UserSerie", i'm not 100% sure which one, rather just as I wrote
has_many :users, :through => :user_series
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜