Rails routing issue, can't figure out the link path - ruby-on-rails

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.

Related

Ruby on Rails page control

I'm sorry, my English is bad. Question: I have model Pages with columns title, description etc. I can create, change, destroy these pages. I can see the contents of the link mydomain/pages/1. I need for each page has been template and route, so I can see the content on the link, for example maydomain/contacts. How to do it? Help me please.
One way to implement your own solution is to add this to your routes file:
get '/mydomain/:slug, to: 'pages#show'
This is a pretty general matcher, so add it to the bottom of your routes so it doesn't override others.
Then your controller show action will look something like:
def show
#page = Page.find_by_slug(params[:slug])
end
This of course assumes you have a slug column on your Pages table.
I'm assuming by "mydomain" you mean the root url of your site (e.g. myapp.example.com)
I'd suggest that you separate the problem into two parts:
Use an attribute other than id to identify an item in the url
Reduce the route so that the controller does not need to be specified.
For 1, have a look at this: Rails routes with :name instead of :id url parameters Note, that as #spickermann suggests friendly_id could be a good solution for you.
For 2, you will need to create a route without the controller name, and then specify the controller in the route definition. (See the Rails Routing Guide):
get ':param', to: :show, controller: 'pages'
For that to work, you will need to put it after (lower in routes.rb) so that it doesn't intefer with other routes. I'd also recommend adding a constraint to the route - to limit the wrong urls that could be routed to that rout.

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".

Rails period inside of url

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.

routes.rb and controller

Sorry, I thought I understood this, but now I have to re-evaluate my understanding of routes.rb. Hoping you could help.
A browser request goes to the Application Controller and the Controller tells what to show, right? - what erb file, database stuff, whatever...
In my routes.rb file I have:
root :to => 'static_pages#FAQ'
Until lately I thought what was happening was: routes.rb is looking at my static_pages_controller.rb file, looking at the FAQ method, and then seeing what to do. If there's nothing in the FAQ method - as is the case - then Rails does its magic and goes to my FAQ.html.erb in my View, the closest thing.
But even if I change the name of:
def FAQ
end
in my controller, or delete the static_pages_controller.rb altogether, it still goes to my FAQ.html.erb file. So does routes.rb not even look at controllers? Does it go straight to 'View' files? Thanks for any help.
static page are served first so that is why FAQ.html.erb is always served.
Also "A browser request goes to the Application Controller and the Controller tells what to show, right? - what erb file, database stuff, whatever..."
I think of it this way: The request first goes through routing, then to the controller for the resource in question, the controller being inherited from application_controller, will then query the model as needed, calculating variables as needed which it then uses in comiling the View page, which are compilation, gets sent as HTML.
Your ideas are essentially correct; Rails will attempt to render the static_page's controller's FAQ method, which implicitly renders the "FAQ" view, if no view (or other output) is explicitly rendered by the action.
What you're missing is that Rails will fill in the blanks if any one of the controller/action pieces is missing. All you need to do is define the view and Rails will assume that you're simply not bothering to define an empty action.
Starting a method name with a capital letter seems like a very bad idea in ruby, because ruby will treat any identifiers that start with a capital letter as a constant. The very first thing I would do personally is change 'FAQ' to 'faq' in my routes and controller code. If you really want to have 'FAQ' capitalized in the browser url, you can probably accomplish that via something like:
root :to => static_pages#faq, :as => 'FAQ'
To check that your method is getting called, use the logger:
def faq
Rails.logger.warn "faq method did get called after all"
end

rails_3_question :as => why is my /posts/new routing to posts/show after setting up a slug

I'm using Rails 3 and after setting up slugs, I found that posts/new no longer works.
posts/:id, posts/:id/edit and all the other CRUD operations work.
However /posts/new gives me a routing error
No route matches {:action=>"show", :controller=>"posts"}
Now for some reason posts/new is routing to posts#show. In my routes, its just
resources :posts
My theory is that since /posts/:slug now matches against things other than numbers ids, the show verb is being routed to first. However it doesn't make sense since posts/grr a nonexistent entry gives a different error than posts/new and posts/first comes out just fine with all its associated paths working fine as well.
Anyone know what might be going on?
I've uploaded the repo to https://github.com/cultofmetatron/cassowary/tree/photogallary
I know my code sucks, I'm still learning the ins and outs of the system and I'd appreciate any insight into whats going on.
In your comment the first part seems fine: add a column to the Post column called slug and so on, and the contents of that will become some or all of the URL used to display a specific post. (I'll assume the other CRUD operations should work as normal)
To find the URL, the router has to know how to know which controller and action will handle this URL (as compared to others). A normal resources :posts route will match all of the RESTful methods, e.g. mapping a GET request onto a path starting with the controller name, and if an id is specified (/posts/1) map to the posts#show controller method, if not, it will map to posts#index method. If the request is a PUT, or DELETE or POST, different actions around a standardized URL format will occur.
Two changes are needed:
URL with the post slug format needs to map to the posts#show method (which is modified accordingly), and
Any links to the show page that are generated on your site need to use the post slug instead of the id
I'll assume you're OK with URLs start with /posts (if not, you'll need to identify some other unique pattern).
The first change requires that you override the specific case of the show method using route globbing, my adding something like match 'posts/*slug before the standard resource route. Here's a link to the guide on route globbing: http://guides.rubyonrails.org/routing.html#route-globbing
The next change, modify the existing posts#show method so that it looks for slug instead of id, e.g.
def show
#post = Post.where("slug = ?", params[:slug])
...
end
Finally, change the way Rails handles the URL helper posts_path. Do this by overriding to_param in your Post model, e.g.
def to_param
"/posts/#{slug}"
end
And then you're done. Maybe.
After that, see how the friendly_id gem does the same thing :-) https://github.com/norman/friendly_id

Resources