Ruby on Rails SQlite 3 database query - ruby-on-rails

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
Index all posts then use
#posts = Post.all
you want to show specific post ,find it by id
#post = Post.find(params[:id])
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

Related

ajax-datatables-rails, passing ids of records from get_raw_records to view

I am using the gem ajax-datatables-rails and manage to build a table that works pretty well.
I would however to retrieve the list of IDs of my records at the get_raw_records function levels, before the data gets processed and formatted.
The reason is because I am using filters and I would like to call an action in the view that will affect ONLY the records filters (not only the ones in current page).
Could you please help me ?
my method looks as:
def get_raw_records
query = Book.where(user_id: user.id)
query = query.where(subject: params[:subject_id]) if params[:subject_id].present?
query
end

Find records related to other records in controller (ruby on rails)

I'm grabbing a list of users and storing in #users.
Now I need to find properties related to only this list of users I have queried.
if params[:company].present?
#users = User.where(parent_id: params[:company]).or(User.where(id: params[:company]))
##properties = #properties.where(user_id: params[:company])
end
I would basically like to include #users inside #properties.where()
I need to get each property that has a user_id present in my #users array
edit:
I just did the following which gives me the result, however, I'm sure there's a much better way of doing this via activerecord:
ids = []
#users.each do |user|
ids.push(user.id)
end
#properties = #properties.where(user_id: ids)
#properties.where(user_id: #users.ids)
That should work. It'll take the id of user ids and perform a filter using the IN clause.
Perhaps adding your models and their relationships we can think about something better.

Ruby on Rails controller order with strings

So I'm trying to organize one of my views so that the articles of my website are listed by the name of the title. For example some of my articles are named "article pt.1, history pt.2, society pt.1, etc". I do have them sorted correctly using this line of code in the Articles controller
def index
#articles = Article.order(:user_id)
end
It does work using the user id, but if I wanted to add another category and have them in alphabetical order, I would need to update the user id of each article which is not practical as they number a little over 200 in the database. What I would like to is somehow take a partial of the article title and sort each one like I am with the user_id field. This way I can sort each one using the string partial such as "article" from "article pt.1"
Thank you for reading and have a wonderful day!
Why not just sort by the title? Assuming you have a column in your articles table called title:
For alphabetical order
def index
#articles = Article.order(:title)
end
For reverse alphabetical order
def index
#articles = Article.order(title: :desc)
end
If you really want to just sort by a substring of the title. You'll have to add a new column to the articles table (called slug in this example):
rails g migration AddSlugToArticles slug:text
rails db:migrate
Then you'll have to update the slug field of every record
Article.all.each do |article|
new_slug = #your code to generate substring here
article.update(slug: my_string
end
then order by slug:
def index
#articles = Article.order(:slug)
end
First of all, it is not very clear about the output that you want, but based on assumption and the description mentioned in the post, it seems like you want to sort the string field not based on whole value but based on substring.
It is better to use the order to get the strings alphabetically sorted.
#articles = Article.order(:title)
And it will also serve the purpose as it will first match the first alphabet of each string and also handle null values at the same time.
Why write a custom logic if the purpose is fulfilled by an already defined method.
I was able to do it using the sort function instead of order using the :title field on the articles controller.
def index
#articles = Article.sort(:title)
end

Rails active record query for search filters

Looking at the railscasts.com, I am wondering how Ryan implemented the search filters for the site. If the search param does not match anything in the database, then he is returning ALL records (for example, if we type an invalid param for the search param value in the URL, all records are returned because there is nothing to filter on). If it matches records in the database he is returning only those matching records.
How is being achieved? Can I use only Active Record without any gems/full-text-search for this? How would that query look like with Arel?
Also, how does he implement the filters link (links at the top of the page after we do a search)? Is he parsing through each of the search params and generating the links on the page by stripping out the search params one at a time?
I do not see Railscasts.com is showing all records when invalid filters (like search parameters). When no record is found, it is returning a link to see all episodes. For example, see this link:
http://railscasts.com/episodes?utf8=%E2%9C%93&search=
It says:
No episodes found. See all episodes.
However, you can show all records in such cases if you want. it's very easy.
def index
#records = []
if params[:search].present?
#YOUR SEARCH LOGIC and assign to #records. for example:
#records = Episode.where(:title => params[:search])
end
unless #records.length
#records = Episode.all
end
end

Paginate data from two models into one newsfeed: Ruby on Rails 3 // Will_paginate

I'd like to make a newsfeed for the homepage of a site i'm playing around with. There are two models: Articles, and Posts. If I wanted just one in the newsfeed it would be easy:
#newsfeed_items = Article.paginate(:page => params[:page])
But I would like for the two to be both paginated into the same feed, in reverse chronological order. The default scope for the article and post model are already in that order.
How do I get the articles and posts to be combined in to the newsfeed as such?
Thanks!
EDIT: What about using SQL in the users model?
Just wondering: maybe would it be possible define in User.rb:
def feed
#some sql like (SELECT * FROM articles....)
end
Would this work at all?
in my last project i stuck into a problem, i had to paginate multiple models with single pagination in my search functionality. it should work in a way that the first model should appear first when the results of the first model a second model should continue the results and the third and so on as one single search feed, just like facebook feeds. this is the function i created to do this functionality
def multi_paginate(models, page, per_page)
WillPaginate::Collection.create(page, per_page) do |pager|
# set total entries
pager.total_entries = 0
counts = [0]
offsets = []
for model in models
pager.total_entries += model.count
counts << model.count
offset = pager.offset-(offsets[-1] || 0)
offset = offset>model.count ? model.count : offset
offsets << (offset<0 ? 0 : offset)
end
result = []
for i in 0...models.count
result += models[i].limit(pager.per_page-result.length).offset(offsets[i]).to_a
end
pager.replace(result)
end
end
try it and let me know if you have any problem with it, i also posted it as an issue to will_paginate repository, if everyone confirmed that it works correctly i'll fork and commit it to the library. https://github.com/mislav/will_paginate/issues/351
for those interested, please check this question: Creating a "feed" from multiple rails models, efficiently?
Here, Victor Piousbox provides a good, efficient solution.
Look at paginate_by_sql method. You can write unione query to fetch both articles and posts:
select 'article' as type, id from articles
union
select 'post' as type, id from posts
You can paginate both if you use AJAX. Here is well explained how to paginate using AJAX with WillPaginate.
You can paginate an array using WillPaginate::Collection.create. So you'd need to use ActiveRecord to find both sets of data and then combine them in a single array.
Then take a look at https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/collection.rb for documentation on how to use the Collection to paginate any array.

Resources