简体   繁体   English

Ruby on Rails SQlite 3数据库查询

[英]Ruby on Rails SQlite 3 database query

I have been looking online about how to do queries for Ruby on Rails and I can find information how to build the query but not where I put the physical code. 我一直在网上寻找有关如何对Ruby on Rails进行查询的信息,我可以找到有关如何构建查询的信息,但是找不到放置物理代码的位置。 I am very new to Ruby on Rails. 我是Ruby on Rails的新手。

I have one database called story and it has the title and content columns that I made. 我有一个名为Story的数据库,它具有我创建的title和content列。 I have a page that is used to input the title and content and then stored into the database and then I have a page which displays all contents of the database but I do not understand how to do a query to find let's say, "a record that has a content or title that contains a certain word or phrase" 我有一个页面,用于输入标题和内容,然后将其存储到数据库中,然后有一个页面,显示数据库的所有内容,但我不了解如何执行查询以找到“记录”其内容或标题包含某个单词或短语的“

   <%= @story.content %>

So i understand that displays the content on the screen, do i just do the same thing for queries? 因此,我知道可以在屏幕上显示内容,我是否对查询执行相同的操作?

In rails active records are used not direct sql queries 在Rails中使用活动记录而不直接执行SQL查询

here's a good link that explains it ...... 这是一个很好的链接,对其进行解释……

http://guides.rubyonrails.org/active_record_querying.html http://guides.rubyonrails.org/active_record_querying.html

For example lets say you have post model and you want 例如,假设您拥有职位模型,并且想要

  1. Index all posts then use 为所有帖子编制索引,然后使用

    @posts = Post.all @posts = Post.all

  2. you want to show specific post ,find it by id 您想显示特定的帖子,按id查找

    @post = Post.find(params[:id]) @post = Post.find(params [:id])

  3. create a new post by 创建一个新帖子

    @post = Post.new @post = Post.new

As per your query, In your controller Write like 根据您的查询,在您的控制器中写为

@stories = Story.where("stories.content IS NOT NULL")  #Records those has a content
@stories = Story.where("stories.title LIKE%a_certain_word_or_phrase%") # Records that contains a certain word or phrase

If you want to pick up only one recoed from the databse you can user .first .last for example 如果您只想从数据库中选择一个已录音,则可以使用.first .last例如

@sotory = Story.where("stories.content IS NOT NULL").first #first item which has content
@sotory = Story.where("stories.content IS NOT NULL").first #last item which has content

You can also find by id like 您还可以通过ID查找

@story = Story.find(1) # finds the record with id = 1

and so on ...... 等等 ......

I think you need a good tutorial.As you are a newbie please checkout Ruby on Rails Guides: Active Record Query Interface 我认为您需要一个很好的教程。作为新手,请查看Ruby on Rails指南:Active Record查询接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM