简体   繁体   中英

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. I am very new to Ruby on Rails.

I have one database called story and it has the title and content columns that I made. 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

here's a good link that explains it ......

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

  2. you want to show specific post ,find it by id

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

  3. create a new post by

    @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

@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

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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