Ruby on rails 别名为的ActiveRecord组
这里有史以来的第一个问题,也是编写完整应用程序/Rails的新手 我创建了一个方法来获得作者对标题的计数,并注意到,如果作者的案例不同,它将被视为不同的作者。我想进行某种验证/检查,以忽略外壳并将其计算在一起。我不在乎在这种特殊情况下书名的大小写 我有一张这样的桌子:Ruby on rails 别名为的ActiveRecord组,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,这里有史以来的第一个问题,也是编写完整应用程序/Rails的新手 我创建了一个方法来获得作者对标题的计数,并注意到,如果作者的案例不同,它将被视为不同的作者。我想进行某种验证/检查,以忽略外壳并将其计算在一起。我不在乎在这种特殊情况下书名的大小写 我有一张这样的桌子: Author Book Title Year Condition William Shakespeare Hamlet
Author Book Title Year Condition
William Shakespeare Hamlet 1599 Poor
Stephen King The Shining 1977 New
Edgar Allen Poe The Raven 1845 Good
JK Rowling Harry Potter and the Sorcerer's Stone 2001 New
edgar allen poe The Tell-Tale Heart 1843 Good
JK Rowling Fantastic Beasts and Where to Find Them 2001 New
def self.book_counts
distinct_counts = []
Book.group(:author).count.each do |count|
distinct_counts << count
end
distinct_counts
end
我想输出以下内容:
Author Count
William Shakespeare 1
Stephen King 1
Edgar Allen Poe 2
JK Rowling 2
我的方法最初是这样的:
Author Book Title Year Condition
William Shakespeare Hamlet 1599 Poor
Stephen King The Shining 1977 New
Edgar Allen Poe The Raven 1845 Good
JK Rowling Harry Potter and the Sorcerer's Stone 2001 New
edgar allen poe The Tell-Tale Heart 1843 Good
JK Rowling Fantastic Beasts and Where to Find Them 2001 New
def self.book_counts
distinct_counts = []
Book.group(:author).count.each do |count|
distinct_counts << count
end
distinct_counts
end
3) 我甚至尝试测试一个不同的简化函数,看看它是否能工作,但我得到了“ActiveRecord::StatementInvalid(PG::GroupingError:ERROR:column“books.author”必须出现在GROUP BY子句中或在聚合函数中使用)”:
4) 我尝试过其他各种方法,但也有其他不同的错误,例如“未定义的局部变量或方法‘dc_auth’”,“未定义的方法‘group’您是指group_by吗?”,以及“参数数量错误(给定1,预期为0)”(使用group_by),等等
这个查询在postgresql中的工作方式正是我所希望的。当我运行#2时,语法实际上会在终端中填充,但正如前面提到的,不幸的是,由于ActiveRecord在Rails中没有正确输出
SELECT lower(author) as dc_auth, count(*) as book_count FROM books GROUP BY dc_auth;
有没有办法通过Rails运行我想要的东西 也许你可以试试
Book.group("LOWER(author)").count
您可以使用ActiveRecord执行查询。我建议使用SQL块
book_count_query = <<-SQL
SELECT lower(author) as dc_auth, count(*) as book_count
FROM books
GROUP BY dc_auth;
SQL
1- result = ActiveRecord::Base.connection.execute(book_count_query)
or
2- result = ActiveRecord::Base.connection.exec_query(book_count_query)
book\u count\u query=为什么将作者与书籍存储在同一个表中。更好的解决方案是为作者添加一个单独的表,并将一个外键添加到author\u id
到books
表中。使用counter\u cache
可以轻松计算每个作者的图书数量
这是一本指南,里面有书籍
和作者
示例wowowowo我的头撞在桌子上了。我发誓当我尝试这个的时候,它不起作用!现在当然你的代码和我最初的一样(Book.group(lower('author')).count.each do | count | distinct | u counts)嗯,很有趣!SQL似乎更容易接受这些函数,所以要么使用该DB,要么强制它使用该语法?我从未见过ActiveRecord::Base.connection.execute/exec_查询方法之前,谢谢你的思考!是的,我喜欢ActiveRecord::Base.connection.execute/exec\u query
。太棒了:)明白了。我不太确定如何轻松地执行该路线,尤其是当将其与我的应用程序中的其他方法绑定时,我认为这可能更容易调用,但我猜事实并非如此。我得再想一想这个问题。谢谢你的意见!
book_count_query = <<-SQL
SELECT lower(author) as dc_auth, count(*) as book_count
FROM books
GROUP BY dc_auth;
SQL
1- result = ActiveRecord::Base.connection.execute(book_count_query)
or
2- result = ActiveRecord::Base.connection.exec_query(book_count_query)