Sorting data from database with Rails - ruby-on-rails

I suspect my question is stupid and answer is obvious, but I TOTALLY stuck with it.
In controller movies_controller.rb I have method index, which fills the array #movies with values from database by calling #movies = Movie.all, and method sort, which do almost the same, but use #movies = Movie.order(:title) instead.
If I call sort explicitly from index what I see in View Index.html.haml is sorted by title list of movies as I expect. But, how can I call method sort by clicking on link? I try
In Index.html.haml:
%th= link_to 'Movies title', 'movies', :on_click => 'self.sort'
In routes.rb:
match ":controller => movies, :action => sort" => 'movies/index'
and nothing is happening, method sort never executes. Actually, I have no idea how to do it right. Looks like it is obvious for everyone, but me.
Can I find short answer how to do it right? Please, kick me in right direction!

If you are looking for sorting data in table then you need some plug in to in place sort the table according to some attribute. following jquery plugin help you to do that,
https://github.com/linjunpop/jquery-tablesorter-rails
or you can achieve the same with background sorting with order clause. check out the following,
http://railscasts.com/episodes/228-sortable-table-columns

For quick and easy you can use 'ransack' gem.
For some writing by yourself check this out http://railscasts.com/episodes/228-sortable-table-columns

Related

Rails Modify Array in Loop

I thought this would be a simple task, but I'm finding it difficult to make Rails do what I want.
I've got an array of dates.
So I thought that something like this would work:
def index
#datetimes = Books.all.map(&:checkouts).flatten.map(&:out_date)
#datetimes.each do |c|
c.to_date
end
end
Then I can just call this in my view:
%ul
-#datetimes.each do |c|
%li=c
How do I modify each key in the array? What am I missing here?
Thanks, so much for being nice to new, novice, and ignorant hobbyists like myself.
.each doesn't modify the caller. It simply loops through. You could change the controller action to just this:
#datetimes = Books.all.map(&:checkouts).flatten.map{|e| e.out_date.to_date}
You might also want to explore including :checkouts in your Books query to avoid N+1 queries. Or perhaps doing something like this maybe.
Checkout.where("book_id is not null").map{|e| e.out_date.to_date}

How would I go about forming this controller correctly in Rails?

How would I define in my controller to run and do the following when the Class is fetched in URL;
I need to find all "jobs" to current_user I'm guessing something like this;
#joblisting = current_user.Joblisting.find(params[:id])
Then I need to take those jobs and check if their column "job_status" has the text "completed" in them or other"
If the jobs_status is "completed" then I need to run code so I do an "if"
I would have to pass the calculation.
#joblisting = current_user.Joblisting.find(params[:id])
if #joblisting.where(:project_status => "completed")
number_to_currency(current_user.Joblisting.where(:project_status => 'completed').sum('jobprice') * 1.60 - current_user.Joblisting.where(:project_status => 'completed').sum('jobprice'))
Notifier.notify_payout(current_user).deliver
#joblisting.project_status = 'paid'
#joblisting.save
end
This is what I've got and I'm stuck with passing the calculation to the Notifier.notify_payout template.
I'm sure whomever knows rails better then me, will right away see my mistakes.
My answer will not give you the code you seek. I'm doing this because I feel like you still have a lot to learn, but I will tell you what to do, just not give you the code. If you say that this line of code works....
#joblisting = Joblisting.where(:developer_id => current_developer[:id])
if #joblisting.where(:project_status => "completed")
Notifier.notify_payout(current_developer).deliver
end
then so be it. As for updating the :project_status column from "completed" to "paid", there can be multiply ways to handle this. You could create a method inside your model (let's call it project_is_paid) that changes project status to paid and declare it inside notify_payout method on success.
But that might be confusing for someone else looking at your code and wondering why all of a sudden the record is changing from "completed" to "paid" inside the database. Plus you would have to pass the joblisting object as an argument which is even more work.
Another way to think of it is to just write a simple conditional statement inside the controller. If the mail is delivered, then call the method project_is_paid. Just be careful not to start adding all this logic to your controller, your controller should be concise and short. Let the model deal with the logic.
I want to conclude with going back to your working controller code you posted. I'm willing to bet that you can turn the two following lines into one.
#joblisting = Joblisting.where(:developer_id => current_developer[:id])
if #joblisting.where(:project_status => "completed")
Why do I say that? Well you are making two queries to the same table Job Listings. Here is a little help if you can't figure out how... link
And if I failed to answer your latest question in the comments, I'm sorry. Post an update in your question and I would be happy to update my own answer.

Difficult search in ruby on rails

How can I search first in model (i know how to do this). And then search in this array for more concretence? As you see:
#articles = Article.find(:all, :conditions => { :ART_ID => #search.map(&:ARL_ART_ID)})
#a = #articles.find_all{|item| item.ART_ARTICLE_NR == search.upcase }
First i search in model, but thanks to my db) it have many wrong results, so i must to clarify my array. But there how to search like sql:
like % %
Now it search very strong: if i search AC451, it's good, but if AC45 or C451 it's nothing fetches. How to say him so that before and after
search
could be everything?
Like this, maybe?
item.ART_ARTICLE_NR.include?(search.upcase)
You are asking for trouble by not following rails naming conventions an using upper case column names. That said, the rails3 way to do it is probably:
#articles = Article.where(:ART_ID => #search.map(&:ARL_ART_ID)).where('ART_ARTICLE_NR LIKE', "%#{search.upcase}%")
Without knowing what #search is, it's hard to be sure. But you should read up on the active record guide on the rails 3 query format.
It's maybe not straigtforward answer, but have you considered using ransack gem?

Rails - Efficient way of finding entries with specific value in model

So I am trying to find all entries in my table that have a specific value in a particular column. The only way I can think off to do this is to look at each entry and see if it has the value but I was hoping there would be a more efficient solution - this gets unwieldy once you have a sizable database.
Does anyone have a better idea?
Update - I am creating an HTML table and I want to populate the table with all the entries in my model that have a certain value in a particular column. I am trying to do:
<%= render #users.where("column_name = 'value'") %>
as the answer below recommends but I get "undefined method `where' for nil:NilClass" error.
Update 2 - I am not sure why #users would be nil but I will try to figure that out later. For now, I tried
<% #user_message = User.where("column_name = 'value'") %>
<%= render #user_message %>
but it doesn't show any entries at all.
Update 3 - When I do, User.all in rails console, I get all the users so I know the data is there. However, when I do User.where("column_name = 'value'"), I get an empty array. I double checked the column name and value to make sure that the data was present.
Update 4 - Fixed! - I'm not sure why it didn't work in rails console but I got it to work in the site. I called my partial _user_message.html.erb. Apparently it still needs to be called _user.html.erb. Thanks for the help everyone!
Sounds like you want to do a where query, i.e.
#records = Model.where(:some_column => some_value)
Rails has excellent documentation, I suggest you take a look at the ActiveRecord Query guide:
http://guides.rubyonrails.org/active_record_querying.html
ian.

rails/activerecord search eager loaded associations

I have a simple find statement as such:
m = MyModel.find(1, :include => :my_children)
With m.mychildren being an Array; is there anyway to find a particular record from within the array without having to iterate over the entire thing. If I do mychildren.find(1), a new DB query is issues, which doesn't make sense, since they are all loaded already
It looks like there's a little Rails magic going on here. Where Enumerable#find is being overridden by ActiveRecord::Base#find on methods created for associations.
On the upside Enumerable#find is aliased to Enumerable#detect.
Unfortunately Enumerable#find/Enumerable#detect have significantly different syntax from ActiveRecord::Base#find.
So you can't just do mychildren.find(1), instead you've got to do mychildren.detect{|c| c.id == 1} if you want to avoid hitting the database again. You may also want to consider extending Array for a more DRY way of doing this.
class Array
def id_find id
self.detect{|element| element.id == id}
end
end
I'm not quite sure what your asking, but have you tried select:
m.mychildren.select{ |child| child == <<some_statement>> }
This won't hit the database assuming you've used the :include option as you stated in your question.
Alternatively, if you know the number of the child you want, you should be able to just use
m.mychildren[1]

Resources