HABTM 查询帮助 (Rails 3)
我有以下模型:
#user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
#group.rb
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
#join table migration
class CreateGroupUserJoinTable < ActiveRecord::Migration
def self.up
create_table :groups_users, :id => false do |t|
t.integer :user_id
t.integer :group_id
end
end
def self.down
drop_table :groups_users
end
end
我需要进行以下查询:
@group = Group.find(:all, :include => users, :conditions => ["users count < ?", group_size]).first
但这给了我以下错误:
SQLite3::SQLException: near "count": syntax error: SELECT "groups".* FROM "groups" WHERE (users count < 2) LIMIT 1
我也尝试过这个:
@group = Group.where("users count < ?", group_size).first
但我得到了同样的错误。我做错了什么?
I have the following models:
#user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
#group.rb
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
#join table migration
class CreateGroupUserJoinTable < ActiveRecord::Migration
def self.up
create_table :groups_users, :id => false do |t|
t.integer :user_id
t.integer :group_id
end
end
def self.down
drop_table :groups_users
end
end
I need to make the following query:
@group = Group.find(:all, :include => users, :conditions => ["users count < ?", group_size]).first
But this gives me the following error:
SQLite3::SQLException: near "count": syntax error: SELECT "groups".* FROM "groups" WHERE (users count < 2) LIMIT 1
I've also tried this:
@group = Group.where("users count < ?", group_size).first
But I get the same error. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想这可能会为你做...
I think that'll probably do it for you...
users.count 是您所需要的 - 请注意您留了一个空格。您收到语法错误,而不是一些奇怪的错误。
现在,如果您确实只想要第一个条目,那么您应该这样做:
注意我正在调用
#first
,而不是#find
。#find
将很快被弃用 - 请使用#all
和#first
代替。users.count is what you need - notice you left a space. You're getting a syntax error, not some strange error.
Now, if you only really wanted the first entry, you should really do:
Notice I'm calling
#first
, not#find
.#find
will be deprecated shortly - use#all
, and#first
instead.