Rails period inside of url - ruby-on-rails

I am having trouble getting rid of a period inside of my url. I've look up others solution to this problem but either of them were for the index action.
Here is what a url looks like
/shared_songs.32 #current url structure
/shared_songs/32 #would like this format
Here is what is inside of my routes.rb
get 'shared_songs/:note_id' => "shared_songs#show" #works fine
get 'shared_songs', to: "shared_songs#index", as: "shared_songs" #/shared_songs.32
Inside of my index.html.erb file I currently have
link_to song.name, shared_songs_path(song)
Any idea how to resolve this problem?

The reason this is happening is because you are taking a url helper that doesn't have any dynamic segments (:id, :user_id etc.) in the path, but you're giving it a value anyway (song). Not knowing what else to do with it, rails uses that value as the format, which is why you end up with /shared_songs/32
shared_song_path(song) doesn't work because you don't current have a route called shared_song. As several of the comments say, by far the easiest way is to do
resources :shared_songs
This will give you a functioning shared_songs_path (for the index, doesn't expect any arguments_ and shared_song_path (requires a parameter). You'll have to change your controller slightly because the the id of the song will be in params[:id] instead of params[:note_id]

Instead of:
link_to song.name, shared_songs_path(song)
Do:
link_to song.name, shared_song_path(song)
song, not songs

It might help if you define your routes in a RESTful manner: something like resources :shared_songs. As explained much more clearly in the Rails docs, using the resources helper will automatically set up appropriate routes to the corresponding controller actions.

Related

How does Airbnb route each article?

I am making a website with Ruby on Rails, referencing Airbnb, and I found it difficult to make the following URL structure.
https://www.airbnb.com/help/article/767/what-is-the-resolution-center
In this URL, it seems that there is an article resource under help, so 767 is the ID of the article. In addition, after the ID, there is the name of the page in the URL.
scope '/help' do
resources :articles
end
By doing this, I was able to route until this part.
/help/articles/'page_id'
But I have no idea what to do from here.
I generated article model(title:string, content:text), and I am guessing that each article(title and content) is displayed according to the id.
Here's my questions.
How does Airbnb route page_name after the article ID?
In the case that the title and content in the article table are displayed, how do you put hyperlinks or internationalize the contents with I18n?
Also, please tell me if my guess is wrong in the first place, and tell me how Airbnb routes each article.
Thank you.
To tell Rails to accept request under URL like /help/article/767/what-is-the-resolution-center is actually very easy when you do use get instead of nested resources:
get '/help/article/:id/:slug', to: 'help_atricles#show', as: 'help_article'
Given the above URL, Rails would extract the id and slug from the URL and route the request to the show method of a HelpArticlesController.
That controller method could be as simple as:
def show
#article = HelpArticle.find(params[:id])
end
And to build such URLs you can use the help_article_path helper method defined by the as: 'help_article' part:
<%= link_to(
#article.title,
help_article_path(
id: #article.id,
slug: #article.title.parameterize
)
) %>
Read more about this routing method in the Rails Guides
Btw. I didn't use the slug part of the URL because it feels to me like it makes the URL look nicer and might be SEO relevant, but it feels useless from the application's point of view. You might want to use the slug part to identify the locale in which the article should be shown if you do not want to use the browser's locale setting.

Rails routing issue, can't figure out the link path

Let me fair from the outset, and tell you that I've 'solved' the problem I'm describing. But a solution that you don't understand is not really a solution, now is it?
I have a resource, Newsbites. I have an index page for Newsbites. All my CRUD actions work fine.
I created a separate index (frontindex.html.erb) that acts as the front page of my website to show the newest Newsbites. The formatting is different from my normal index so readers get a larger photo, more of the text of the article(more ads too:).
In my routing table, I have the following statements:
resources :newsbites
get 'newsbites/frontindex'
root 'newsbites#frontindex'
Rake routes show the following:
newsbites_frontindex GET /newsbites/frontindex(.:format) newsbites#frontindex
If I load my website from the root (localhost:3000), it works great. There is a separate menu page that is rendered at the top, and it loads fine. I can click on all links, except the 'Home' link, and they work fine.
The 'Home' link is:
<%= link_to 'Home', newsbites_frontindex_path %>
When I click on the linked, I get the following error:
Couldn't find Newsbite with 'id'=frontindex
The error points to the 'show' action of my Newbites controller. Here are the frontindex and show def from the controller. They appear exactly as I'm posting them:
def frontindex
#newsbites = Newsbite.all
end
def show
#newsbite = Newsbite.find(params[:id])
end
I don't get it. Why is the show action being called by newbites_frontindex_path when there is both a def and views that match? Now, I can get around this by simply pointing home to root_path. But that doesn't help me understand. What if this was not the root of the site?
Any help would be greatly appreciated.
Actually I'm very surprised your code worked at all. A route must define two things
Some sort of regex against which the URL of the user is matched (newsbites/frontindex is different than newsbites/backindex)
What do you want to do for a given URL ? You want to point to a controller action
Rails won't usually "guess" what that action is. Or maybe, he was still able to "guess" that you wanted to use the newsbites controller, but it didn't guess the action right this time :(.
You should declare the root like this, which is what you did
root 'controller#action'
For the rest, there are two ways you can declare it. I prefer the second one
resources :newsbites
get 'newsbites/frontindex', to: 'newsbites#frontindex'
resources :newsbites do
# stuff added here will have the context of the `newsbites` controller already
get 'frontindex', on: :collection # the name of the action is inferred to be `frontindex`
end
The on: :collection, means that 'frontindex' is an action that concerns ALL the newsbites, so the URL generated will be newsbites/frontindex.
On the other hand get 'custom_action', on: :member, means that the custom_action targets a specific item, the URL generated would look like newsbites/:id/custom_action
EDIT : Rails also generate path_helpers based on the route declaration
get 'test', to: 'newsbites#frontindex'
get 'test/something', to: 'newsbites#frontindex'
resources :newsbites do
get 'frontindex', on: :collection
get 'custom_action', on: :member
Will generate path helpers
test_path
test_something_path
# CRUD helpers : new/edit/show/delete, etc. helpers
frontindex_newsbites_path
custom_actions_newsbite_path(ID) # without s !
You can always override this by adding an as: option
get 'custom_action', on: :member, as: 'something_cool'
# => something_cool_newsbites_path
Rails routes thinks that frontindex is an id. That's what the error message says. So it goes to GET newsbite/:id which maps to show.
You need to find a way let Rails routes know that frontindex is not an id.
On a side note: The order in which you define routes matters. The first one matched will be used. If you have GET newsbite/:id and GET newsbite/frontindex then the one that appears first will be matched. In your case this is the first one.
Maybe try to change the order.

Rails routes and querystring

I am having troubles trying to define the correct route for a query coming from ember. The request appears like this:
GET "/users?id=1011
No matter what I try I always have the request forwarded to the index action, while it is intended for the show action.
I have tried many things, like
get "/users?id=", to: redirect('/users')
but nothing seems to work.
Can anyone explain to me what can I do and most important the reason behind it?
Thank you very much for your time!
GET /users?id=1011 always goes to index because Rails just sees the route as GET /users. The question mark denotes a parameter, which isn't part of any of your defined routes.
You can modify your index method to interpret the param, something like:
def index
if params[:id]
# call show, do something, whatever
else
# regular index action
end
end
In the case of retrieving just one user, it would be more common to route this to your show action as you originally intended. To accomplish this, do not pass the id as a query param, but instead as a slug segment /users/1011, which you can accomplish by declaring the following in your routes.rb:
get '/users/:id', to: 'users#show'
If you want to go full tilt then you might as well just declare users as a resource like so:
resources :users
Which will automatically wire up your index, show, update, destroy, etc. Throw Active Model Serializers in the mix and you can have Ember Data start talking to your API nearly "out of the box".

Sending a variable through a link_to without url query in Ruby on Rails

I'm trying to send a variable through a link_to, without using url query in Ruby on Rails, from one controller's index view to be used on another controller's index.
Basically, I need to pass the Turma.id (school class id), to the Elementos_turma(peoples in the class) controller, so I can use it and filter the index: ElementosTurma.find(:all, :conditions => { :turma_id => xxxxx } ), to show the peoples of the selected class.
It it possible?
Maybe without using a session variable?
Maybe sending the variable to a method on the 1st controller, to send it the other controller? (if so how? not very RoR wise... :) )
No need for a special method to get the info you need, the magic of routes will do.
In your routes.db file, you should be able to define something like this,
map.resources :class, :has_many => :students
Then if you run 'rake routes' you should see a routes similar to this
class_students GET /classes/:class_id/students(.:format) {:controller=>"students", :action=>"index"}
You can call that path in your view like so
class_students_path(class_id)
Then in your controller you will have access to params[:class_id]
The name of the route isn't very pretty, but this should work.
EDIT--------------------------------------
According to your comment, you can't use map.resources for some reason or another...
map.class_students '/:class_id/students', :controller => 'students', :action => 'index'
That will produce the same route available in your view, same param in your controller.
That being said, I don't know how a server bug could prohibit you from using map.resources
You can not transfer data through a link without including that data in the link.
However, it sounds like you just need to be using nested resources. (Since I speak English, I'm going to not tackle another language and do what comes to me.) The URLs you want to be sending people to probably should look more like this if you want to be RESTful:
/classes/1/people/
That is the "Rails way" of indicating that you want to get people in class #1, and Rails offers built-in routing methods to make this easy. See the Rails Routing from the Outside In article in the Rails Guide.

how do I make the URL's in Ruby on Rails SEO friendly knowing a #vendor.name?

My application is in RoR
I have an action/view called showsummary where the ID has been passed into the URL, and the controller has used that to instantiate #vendor where #vendor.name is the name of a company.
I would like the URL to be, rather than showsummary/1/ to have /vendor-name in the URL instead.
How do I do that?
All of these solutions use find_by_name, which would definitely require having an index on that column and require they are unique. A better solution that we have used, sacrificing a small amount of beauty, is to use prefix the vendor name with its ID. This means that you dont have to have an index on your name column and/or require uniqueness.
vendor.rb
def to_param
normalized_name = name.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
"#{self.id}-#{normalized_name}"
end
So this would give you URLs like
/1-Acme
/19-Safeway
etc
Then in your show action you can still use
Vendor.find(params[:id])
as that method will implicitly call .to_i on its argument, and calling to_i on such a string will always return the numerical prefix and drop the remaining text- its all fluff at that point.
The above assumes you are using the default route of /:controller/:action/:id, which would make your URLs look like
/vendors/show/1-Acme
But if you want them to just look
/1-Acme
Then have a route like
map.show_vendor '/:id', :controller => 'vendors', :action => 'show'
This would imply that that it would pretty much swallow alot of URLs that you probably wouldnt want it too. Take warning.
I thought I'd mention String#parameterize, as a supplement to the tagged answer.
def to_param
"#{id}-#{name.parameterize}"
end
It'll filter out hyphenated characters, replace spaces with dashes etc.
Ryan Bates has a great screencast on this very subject.
Basically you overload the to_param method in the Vendor model.
def to_param
permalink
end
Then when you look up the resource in your controller you do something like this:
#vender = Vender.find_by_name(params[:id])
But the problem with this is that you'll have to make sure that the vendors' names are unique. If they can't be then do the other solution that Ryan suggests where he prepends the the id to the name and then parses the resulting uri to find the item id.
You do this by modifying the routes that are used to access those URL's and changing them to use :name, rather than :id. This will probably mean that you have to write the routes yourself rather than relying on resources.
For instance add this to the routes.rb file:
map.with_options :controller => "vendor" do |vendor|
vendor.connect "/vendor/:name", :action => "show"
# more routes here for update, delete, new, etc as required
end
The other change that will be required is that now you'll have to find the vendor object in the database by the name not the id, so:
#vendor = Vendor.find_by_name(params[:name])
Internally (at least to my knowledge/experimentation) whatever parameter name is not specified in the URL part of the route (i.e. not within the "/Controller/Action/:id" part of it) is tacked on to the end as a parameter.
Friendly ID
http://github.com/norman/friendly_id/blob/26b373414eba639a773e61ac595bb9c1424f6c0b/README.rdoc
I'd have to experiment a bit to get it right, but there's two primary parts to the solution.
1) Add a route.
in config/routes, add a line that sends requests of the form baseurl/controller/:vendor-name to the action showsummary, (or maybe a new action, show_summary_by_vendor_name)
[also, if you planned on using baseurl/:vendorname, that's fine too]
For convenience, make sure the parameter is something like :vendor-name, not the default :id
2) Write the controller action.
In the controller file, either edit your showsummary action to differentiate based on whether it's called with an id or with a vendorname, or just write a show_summary_by_vendor_name. (depending on best practices, and what route you wrote in 1. I don't know off the top of my head which is preferable)
You can then do
#vendor = Vendors.find_by_name(params[:vendor_name])
or something like that, and then render it the way you would in regular showsummary.
3) Use that as the link.
Once you confirm that baseurl[/controller?]/vendor-name works, and shows the summary, make sure all the links in your application, and elsewhere, use that link. Off the top of my head, I can't remember how difficult it is to integrate a custom route into link_to, but I think it's doable. Most search engines [google] rely heavily on links, so good SEO will have you using those named links, not the numbered ones. I think. I don't know much about SEO.
Take a look also at this quck start to SEO for Rails

Resources