Question about URL friendly links - ruby-on-rails

I am trying to get my urls to look like this:
example.com/posts/id_of_post/title_of_post
I have this in my controller:
match ':controller/:id/:link', :controller => 'posts', :action => 'show'
Say I have a list of posts.. how can I link to them?
<%= link_to 'Show', post %>
Just gives the usual /posts/id
On another note, at the minute I am making a url-friendly link when a post is created and storing it in the database. Would it be better to create on the fly? Is that possible/better?
I saw this in an answer to another question:
def to_param
normalized_name = title.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
"#{self.id}-#{normalized_name}"
end
That would work if I could change the - to a /. Possible?

I recommend just doing this instead of the gsub stuff:
def to_param
"#{self.id}-#{title.parameterize}"
end
Downside is that if the title changes, the URL changes. Which is a downer.
So a lot of implementations will do
before_create :permanize
def permanize
permalink = title.parameterize
end
def to_param
"#{self.id}-#{permalink}"
end

This is what I did:
I added this to my post#create:
#post.link = (#post.title.parameterize)
I will give the user the option to edit the title for up to 5 mins after posting.
My route:
match "/posts/:id/:link" => "posts#show", :as => "story"
and my index view for posts
<%= link_to 'Show', story_url(post, post.link) %>

Related

Ruby on Rails 4: Display Search Results on Search Results Page

I am currently implementing the search functionality in a project and I am struggling displaying it on a dedicated search result page.
Being aware of questions on this topic already but being unable to work out a solution due to utter incompetence, I am asking you for the final pointer :).
The search form spawns on the index page which is entries_path and root_path. I'd like to pass on the parameters to a new page, search_path.
Here are my files:
EntriesController
def search
end
def index
#entries = Entry.all.order('entries.created_at DESC')
#entry = Entry.new # My index page also creates new entries.
if params[:search]
#entries = Entry.search(params[:search]).order("created_at DESC")
else
#entries = Entry.all.order("created_at DESC")
end
Model: entry.rb
def self.search(search)
where("content LIKE ? OR created_at LIKE ?", "%#{search}%", "%#{search}%")
end
routes.rb
Rails.application.routes.draw do
resources :entries
root 'entries#index'
get 'new' => 'entries/new'
get 'show' => 'entries/show'
get 'edit' => 'entries/edit'
get 'search' => 'entries/search'
Finally: the form on index
<%= form_tag(entries_path, :method => "get", class: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search for previous entries..", class: "form-control" %>
<% end %>
When I change the entries_path to search_path, I am getting a "We're sorry, but something went wrong. If you are the application owner check the logs for more information." – therefore, I suspect it is a routing problem. However, I can't seem to figure it out. The log says:
ActionController::RoutingError (uninitialized constant Entries):
Phew, would love to know what's going on here! Thanks a bunch already.
Change your routes.rb
Rails.application.routes.draw do
root 'entries#index'
resources :entries do
collection do
get :search
end
end
end
change your path in search form on index page:
<%= form_tag(search_entries_path, :method => :get, class: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search for previous entries..", class: "form-control" %>
<% end %>
Change your controller's method:
def search
if params[:search]
#entries = Entry.search(params[:search]).order("created_at DESC")
else
#entries = Entry.all.order("created_at DESC")
end
end
create one template for search method under view/entries/search.html.erb
You can here access your #entries object
Points of changes I have made:
1. Changes in routes.rb:
Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
A resource route maps a number of related requests to actions in a single controller. a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. for more information regarding routes
You can add additional routes that apply to the collection or individual members of the collection.
For Eg:
To add a member route, just add a member block into the resource block:
resources :entries do
member do
get 'preview'
end
end
To add a route to the collection:
resources :entries do
collection do
get 'search'
end
end
A member route will require an ID, because it acts on a member. A collection route doesn't because it acts on a collection of objects. for more info about
difference between collection route and member route in ruby on rails?
2. Which method should I use for search GET or POST?
There are numbers of post available regarding GET and POST request on the web as well as SO. GET and POST both have their place, and if you’re a Web developer you should understand the pros and cons of each of them. Or if you’re too lazy to do that, just remember that Search forms should use GET method. Your users will appreciate it. ;)
Let me define them in short description.
GET to fetch a resource(when you don't want to make any change in your DB), POST to create a resource(when you want to make a change/create in your DB), PUT (or PATCH, these is debate on the matter) to update a resource, DELETE to delete one.
For your reference:
When do you use POST and when do you use GET?
I hope this information may helps you. Good Luck :)
You could use html as a search field on Index page.
<form>
<legend>Search</legend>
<div class='col-xs-4'>
<input type='text' class='form-control' value='<%= params[:search] %>' name='keyword' placeholder='Keyword' >
</div>
</form>
Note: This form would hit your index action of entries controller, So at this point no need to create a search methods as you have created

How to make a custom route in Rails? By custom I mean one that reacts to params

So essentially I've setup a route to match "products/:product", which seems to respond to a page like baseurl/products/toaster and displays the toaster product. My problem is I can't seem to use link_to to generate this path, and by that I mean I don't know how. Any help on this?
There are several solutions on this one :
<%= link_to 'Toaster', { :controller => 'products', :action => 'whatever', :product => 'toaster' } %>
But it's not really Rails Way, for that you need to add :as => :product at the end of your route. This will create the product_path helper that can be used this way :
<%= link_to 'Toaster', product_path(:product => 'toaster') %>
Within your routes file you can do something like:
match "products/:product" => "products#show", :as => :product
Where the controller is ProductsController and the view is show
within the Products controller your have
def show
#product = Hub.find_by_name(params[:product])
respond_to do |format|
format.html # show.html.erb
end
end
Where whatever is in the products/:product section will be available via params.
Then, since we used :as in your routes you can do this with link_to:
<%= link_to product(#product) %>
Where #product is an instance of a product or a string. This is just an example and the param can be anything you want, the same goes for controller/action. For more info you should check out this.
Hope this helps!

Rails: link_to calls custom method in controller

I am looking to use link_to to call a method in my controller. However, for some odd reason the route looks for the show method.
In my view:
<% #beverages.each do |beverage| %>
..
<%= link_to 'Archive', beverages_archive_path(:id => beverage.id) %>
..
<% end %>
In my config/routes.rb
match 'beverages/archive' => 'beverages#archive'
In my beverages_controller.rb
def archive
beverage = Beverage.find(params[:id])
respond_to do |format|
# format.html # show.html.erb
format.json { render json: beverage }
end
# beverage.update_attribute('archive', true)
end
When I click on the archive link in the view, the URL does change to: http://localhost:3000/beverages/archive?id=11, however I get the following error.
The error I get:
ActiveRecord::RecordNotFound (Couldn't find Beverage with id=archive):
app/controllers/beverages_controller.rb:46:in `show'
Any idea on what I am doing wrong? Your help is much appreciated!
PS. I also looked at Rails 3 link_to delete destory method calls show method?
but nothing seemed to work.
Have you tried this in your routes?
match 'beverages/:id/archive' => 'beverages#archive', as: :beverages_archive
This will create the beverages_archive_path method for you. Also, as you are looking for a specific beverage, use :id inside the route so that it knows where to take the id parameter from.
Apart from that, you can always tell a link specifically which controller and action to link to by doing:
link_to "Label", :controller => :my_controller, :action => :index
Taken from here: Ruby on rails 3 link_to controller and action
Use the other notation (not match) instead.
resources :beverages do
collection do
get :archive
end
end
Try this one out and let me know if something went wrong.
There's not quite enough information here to know why beverages_archive_path works in your app -- one problem is that your routes file does not define a name for your beverages#archive route. What you want is something like:
match 'beverages/archive' => 'beverages#archive', :as => :beverages_archive
or better yet use resourceful routing conventions like so:
resources :beverages do
collection do
get :archive
end
end
What's happening is that you have a beverages#show route that matches /beverages/:id, and this is what /beverages/archive matches (with :id => 'archive').

Permalink-fu - Display URL differently

I'm using Ruby on Rails 2.3.8 and permalink-fu plugin. I would like to know how to generate permalinks like this: /posts/44444/this-is-the-title instead of /posts/44444-this-is-the-title
I've tried modifying my Post model as follows:
has_permalink :title, :update => true
def to_param
"#{permalink}"
end
And my routes file as follows:
map.show "/posts/:id/:permalink", :controller => 'posts', :action => 'show'
Then, if I manually type the url with that format, it will work, but if I make a link out of a post in my view as follows, it wont generate the link formatted that way:
<%= link_to p.title, p %>
Where p represents a post.
How can I do so when I call a post like that, I get a permalink formatted as /posts/:id/:permalink instead of /posts/:id-:permalink?
Try this one...
on model:
def to_params
[self.id, self.permalink]
end
on views:
<%= link_to p.title, show_path(p) %>

How to add action 'current_user' to a restful 'user'?

I have a model 'User', it's a restful resource, and has the default methods like 'index, show, new, create' and others.
Now, I want to define a new action 'current_user', to show the information of current logged-in user, which is different from 'show'.
When I use:
link_to current_user.name, :controller=>'users', :action=>'current_user'
The generated url is http://localhost:3000/users/current_user, and error message is:
Couldn't find User with ID=current_user
Shall I have to modify the routes.rb? What should I do?
I have searched for some articles, and still have no idea.
Add
map.resources :users, :collection => {:current => :get}
Then, I use:
link_to 'current', current_users_path()
The generated url is:
http://localhost:3000/users/current
Now, everything is OK. Is this the best solution?
See my comment on the other answer for an explanation
map.current_user "users/current", :controller => :users, :action => :current
View:
link_to 'current', current_user_path
I would not add a new action for this. I would check the id passed to the show method.
class UsersController
def show
return show_current_user if params[:id] == "current"
# regular show code
end
private
def show_current_user
end
end
In the view use :current as the user id while generating path.
user_path(:current)

Resources