在 Ruby on Rails 中访问查询
我在我的控制器中有这样的:
@itemsok = Search.where("first_item_id = ?", params["3"])
这是数据库搜索表中的一个查询,要求所有具有first_item_id = 3的搜索...
问题1.-语法是我在http://guides.rubyonrails.org/active_record_querying.html 但我不确定我是否使用对吗?
好的,问题 2 是,我在控制器上有这个,可以在控制器中进行查询吗?
在视图中,我正在打印变量 <%= @itemsok %>我得到的只是一个
ActiveRecord::Relation:0x007fd3d3e894d8
有什么建议吗? 提前致谢。
I have in my controller this:
@itemsok = Search.where("first_item_id = ?", params["3"])
This is sopposed to be a query in the search table of the database asking for all the searches that have a first_item_id = 3 ...
Question 1 .- The syntax is I found it in http://guides.rubyonrails.org/active_record_querying.html but im not sure if im using it right?
Ok the question 2 is, I have this on the controller, is it ok to have querys in the controller?
In the view im printing the variable <%= @itemsok %> and all I get is a
ActiveRecord::Relation:0x007fd3d3e894d8
Any suggestions?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ActiveRecord 3 允许您将关系链接在一起,这样您就可以执行如下操作:
where()
函数返回一个ActiveRecord::Relation
。一般来说,这不是问题,因为如果您使用该对象,它会自动运行查询并返回该对象的结果,以便您获得数据库对象。 AR 在实际需要时才会运行查询。其中将返回项目列表(数组),因此如果您只是在调试,请将视图更改为:
ActiveRecord 3 lets you chain relations together so you can do something like this:
The
where()
function returns anActiveRecord::Relation
. Generally this isn't a problem, since if you use the object it'll automatically run the query and return the results on the object so you'll get the database objects. AR doesn't run the query until it's actually needed.Where will return a list of items (Array), so if you're just debugging, change your view to this:
您似乎以错误的方式构建查询。
如果你想搜索first_item_id = 3的记录,你应该这样做:
Search.where("first_item_id = ?", 3)
这将返回一个匹配记录的数组,这是你无法轻易做到的使用
<%= @itemsok %>
打印。您应该迭代元素并打印每个元素:我还建议为要打印的对象定义
to_s
方法。然后你可以简单地打印该对象,并且将自动为你调用
to_s
方法:You seem to be constructing the query wrong way.
If you want to search for records with first_item_id = 3, you should do:
Search.where("first_item_id = ?", 3)
This will return an array of matching records, something you can't easily print with
<%= @itemsok %>
. You should iterate over the elements and print each one:I'd also suggest defining
to_s
method for the objects you want to print.Then you can simply print the object and
to_s
method will be automatically called for you:正确的方法是在模型中定义一个
namedscope
,然后在控制器中使用它。与此类似:
然后从控制器调用
namedscope
,如下所示:The right way to do is to define a
namedscope
in the model and then use it in the controller.Something similar to this :
and then call the
namedscope
from the controller like this :