Searching based on field content - Ruby on Rails - ruby-on-rails

So I am creating a ruby on rails application and in my view I have a list of link_to with each being a different console
In my database table I have a field called console.
What I want to do is when a user clicks on a link e.g. Playstation 3, it will return back all records that have Playstation 3 listed in that table column.
I was wondering how I would go about doing this, I have tried searching on the internet but have not found anything similar.
It is for a project that I don't have long to complete. I was owndering what I would state in the link to's in the view and what I would put in the games_controller.
Any help would be much appreciated.

The basic gist is to have a controller action which will return the list of games filtering by console. For example,
# GamesController.rb
def index
#games = Game.find_by_console(params[:console])
end
Then you can create a link for any particular console as such:
link_to 'XBOX', games_path(:console => 'XBOX')
This should result in a GET request to the URL /games?console=XBOX
If you've got a pre-defined set of consoles, you might look into making them into constants inside a Consoles module to avoid having to hardcode them everywhere.
UPDATE:
Since you are trying to implement both searching and filtering in the same chain, you need to make sure that find_by_console isn't called if it's not present.
# GamesController.rb
def index
#games = Game.search(params[:search])
#games = #games.find_by_console(params[:console]) unless params[:console].blank?
end

Related

Track Dates of viewed article

I am working through my first Ruby on Rails App!
I have followed along with ruby's getting started tutorial and created a blog. http://guides.rubyonrails.org/getting_started.html
I am trying to implement a way to track when articles are viewed so I created a second table/model/controller that I'd like to insert the current date every time an article is viewed (show).
I'm not really sure how to implement this though... my initial though was in the article controller under the show def I would do something like
#view = View.new(view_params)
#view.Save!
This didn't really work. Any idea at all?
Thanks
You didn't mention what columns you had in your new model, but I'm assuming it's just the default timestamps and a field for the article ID.
So, within the 'show' action for the articles, you could do something like this. Your action names and such may differ, but the principle is the same.
def show
#article = Article.find(params[:id])
View.create(article_id:#article.id)
end
I can't think of any reason why you'd need to store the view itself in an instance variable, or any variable for that matter.

Multiple index actions in Rails

I have a Game model and GamesController. Currently my index page shows first 10 records from the database for the purpose of the application. However, i want to make another page where all of the games are being shown.
My question is, what's the Rails way™ of achieving this purpose? Is it possible to have the index action of my GamesController to make requests based on what URL i want to render? (Something like http:localhost:3000/all)
Rails 3.1 - How do I organize multiple index actions for the same model?
was the closest to my issue, but the question tackles problem from rails 3.1 dating back to 2012.
You can really only have one index action per controller, but there are a couple of ways you can achieve this.
First, simply create a new action and have a separate page. Think of an appropriate name for it and create the controller, route, and view. You can keep the amount of code to a minimum by having much of the view code in a partial and use that in both views.
The other way to do this, if you really only want one action, is to pass a parameter to the index controller and query the database based on that parameter. For instance:
link_to 'link text', game_index_path(:g => 'all')
will create a url like: http://domain.com/game/index?g='all' and in the controller you can do this:
def index
which_games = params[:g] # should be all in this case
#games = Game.where(:criteria => which_games)
end
You can use this same method to implement sorting and filtering and all sorts of things.

Rails param for show page

I've used params in a URL for the index page successfully. But, I'm not getting the same success with the show page.
This is what I'm trying to use:
def show
#workorder = Workorder.find(params[:id])
#workorder = Workorders.where("wonum = #{params[:wonum]}") if params[:wonum].present?
Then I'm trying those URLs:
http://localhost:3000/workorders/?wonum='14-21291'
http://localhost:3000/workorder?wonum='14-21291'
Thanks for the help!
UPDATE 1
Rake Routes:
UPDATE2
What I would really like is this url to work:
http://localhost:3000/workorder?wonum='14-21263'
Could I add a route to the workorder show function?
You are almost there, you just need some minor changes and you'll get what you need.
It's important to understand that rails expects route ids to corrospond to database ids like the following:
http://localhost:3000/workorder/32'
This will save 32 in params[:id]
This is the default behavior and you will see this in all the rails beginner examples.
You will run into problems because you are trying to find Work orders by a different field, not id. So you need to change the code in your workorders controller.
Try this:
def show
#workorder = Workorders.where(:wonum, params[:wonum]).first if params[:wonum].present?
#workorder = Workorder.find(params[:id]) if #workorder.nil?
The major differences are how I call the where method (this way where add security for you) and trying to find a workorder from the :wonum parameter before trying to find it using the id. I suspect in your attempt, you were getting a record not found, or routing exception because you didn't pass in an id at all in your example url.
With an id:
http://localhost:3000/workorder?333wonum='14-21263'
I suggest looking at the sql generated in your rails server window to see what is going on.
You should look at this gem for a cleaner, off the shelf solution to what you're trying to do -> https://github.com/norman/friendly_id/

Changing urls in ruby on rails depending on different conditions

I'm new to ruby on rails....I wanted to know if there is a way to change the URL displayed depending on the client's response. I mean... here's an example:
I'm making a project showing listings in various places...
Now in general I have a home page, a search page, and a detail page for listings. So, respective URLs are officespace/home, officespace/search?conditions, officespace/detailpage?id=(controller-officespace)[&Conditions eg.---price,size,place,type...]
So, every time the client makes a request for search, the same URL is shown, of course with the given conditions.
Now I want that if the client asks for only the place and mentions nothing about size, price, etc., the url should be /listing/location_name.
If he mentions other conditions, then it'll be listing/(office_type)/size(x sq feet)_office_for_rent_in_locationname)
B.t.w. (I already have a controller named listings and its purpose is something else.)
And so on ........... Actually, I want to change URLs for a number of things. Anyway, please help me. And please don't refer me to the manuals. I've already read them and they didn't give any direct help.
This is an interesting routing challenge. Essentially, your goal is to create a special expression that will match the kinds of URL's you want to display in the user's browser. These expressions will be used in match formulas in config/routes.rb. Then, you'll need to make sure the form actions and links on relevant search pages link to those specialized URL's and NOT the default pages. Here's an example to get started:
routes.rb
match "/listing/:officeType/size/:squarefeet/office_for/:saleOrRent/in/:locationName" => "searches#index"
match "/listing/*locationName" => "searches#index"
resources :searches
Since you explicitly mentioned that your listings controller is for something else, I just named our new controller searches. Inside the code for the index method for this controller, you have to decide how you want to collect the relevant data to pass along to your view. Everything marked with a : in the match expressions above will be passed to the controller in the params hash as if it were an HTTP GET query string parameter. Thus we can do the following:
searches_controller.rb
def index
if params[:squarefeet] && params[:officeType] && params[:locationName]
#listings = Listing.where("squarefeet >= ?", params[:squarefeet].to_i).
where(:officeType => params[:officeType],
:locationName => params[:locationName])
elsif params[:locationName]
#listings = Listing.where(:locationName => params[:locationName])
else
#listings = Listing.all
end
end
And to send the user to one of those links:
views/searches/index.html.erb
<%= link_to "Click here for a great office!", "/listing/corporate/size/3200/office_for/rent/in/Dallas" %>
The above example would only work if your Listing model is set up exactly the same way as my arbitrary guess, but hopefully you can work from there to figure out what your code needs to look like. Note that I wasn't able to get the underscores in there. The routes only match segments separated by slashes as far as I can tell. Keep working on it and you may find a way past that.

Custom index views with ActiveAdmin

I'm working on an application with an ActiveAdmin backend and having a hell of a time getting it to render a fairly simple custom index view.
I have a number of 'request' records, which contain an email address and a book_id, by which they need to be grouped. I got as far as:
ActiveAdmin.register Request do
controller do
def index
#requests = Requests.group(:book_id).page
end
end
end
but this resulted in an error: ActiveSupport::OrderedHash can't be coerced into Fixnum
I can create my own custom view in app/admin/requests/index.html.erb but then I lose the standard AA layout with the admin menu et all and can't find a good way to include it.
I ended up doing this using a technique described on their Google Group, in which you just shove the user over to a custom action:
https://groups.google.com/d/msg/activeadmin/YgMzeYBXRno/GZ01Epyq5lcJ
Hacky, yes. I think this is a much needed feature, so hopefully someone can fork and add in support for the index view to take a block with custom content.

Resources