Reputation: 2575
def create
@article = Article.new(params[:article])
@article.save
redirect_to @article
end
def show
@article = Article.find(params[:id])
end
I'm following the Getting Started with Rails guide. I have a form that, upon clicking the submit button, creates an @article
object (a RESTful object) with the form input.
redirect_to @article
sends a GET request to /articles/id
, right? If so, why does this happen? Is this simply how redirect_to
works?
Upvotes: 1
Views: 61
Reputation: 76784
Objects
To add to Nishu
's answer, when you reference an object in any path_helper (link_to
, redirect_to
etc), Rails will do the hard work and show you the route for the object
Remember, Ruby / Rails is an object-orientated framework, meaning everything you do has to revolve around an object. In the case of Rails, objects are populated with data from your models, which is done using ActiveRecord
--
So if you use redirect_to @article
, Rails will basically look for the show
action for that particular record. As your routes should be resourceful - meaning Rails can basically look for the relevant route to display that record on its own
Hope this helps?
Upvotes: 1
Reputation: 1493
redirect_to calls url_for if the argument passed is a Record.
url_for calls to_param on record which by default returns id.
Hence redirect_to @article will generate /articles/:id
Upvotes: 2