Reputation: 4583
I am following this rails guides. And I have this following code
class ArticlesController < ApplicationController
def new
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
In the above code, in the create action, I have modified @article to article_path. Which I believe is the same as per the routes.
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
root GET / welcome#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
# the above route
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
So as per the routes, I mentioned the article_path. But when I did that, it redirects me to /articles instead of /articles/:id
can anyone explain me what is happening.
Upvotes: 0
Views: 1201
Reputation: 3723
This seems pretty obvious to me.
When you redirect to @article you are redirecting to THAT article defined by that instance stored in the variable. This surely means /articles/:id, where :id is the id of THAT article stored in the variable.
But when you redirect to articles_path you're not going to a particular article, but to the URL of all articles, i.e., /articles. If you redirect to article_path (now singular) without telling which article do you want, you are going to be redirected the same, to a point where you may find all articles, i.e., /articles
It is just a question of thinking about the semantics of the REST calls.
Hope it helps!
Upvotes: 2
Reputation: 827
For a correct redirect you have to use redirect_to article_path(@article)
. This way Rails knows to what article it should redirect to.
Upvotes: 1
Reputation: 438
article_path
will need to be called with a param of either article.id
or @article
(an object that responds to to_param
)
Upvotes: 1