user350325
user350325

Reputation: 1455

redirect_to , relationship between controller and model

I generated a scaffold and it makes a controller that looks like this (I stripped some code out but it still works).

  def create
    @post = Post.new(params[:post])

    if @post.save
      redirect_to @post
    end
  end

This causes it to redirect to /posts/id which all works fine.

But I don't understand how this works. @post is an instance of a model class, so how does it know which controller and action it should redirect to? I don't see anywhere that this relationship is explicitly defined (between Post model and PostsController).

I have tried replicated this from scratch without scaffolding and I get errors about being unable to find url_for associated with the models I define. Even when I do define routes with resources in routes.rb.

Upvotes: 2

Views: 74

Answers (2)

ck3g
ck3g

Reputation: 5929

When you call redirect_to it calculates path by calling _compute_redirect_to_location method

And reaches the else statement in that method

And calling url_for method where reaches else as well.

And calls polymorphic_path (and polymorphic_url) here.

Here convert_to_model(record) method has been called.

Where record == @post

Calculating the inflection you will reach else and it's :singular

After you will reach build_named_rout_call

And calls ActiveModel::Naming.singular_route_key(@post). You will get ['post']

After route << routing_type(options) your route is ['post', :url]

Putting @post into args and send("post_url", args) which is same aspost_path(@post)

I'm sorry if I'm wrong somewhere. I hope this will give you understanding of redirect_to @post.

Upvotes: 2

coletrain
coletrain

Reputation: 2849

The reason it still works because in your controller Post create method is still there, which looks normal to me and also in your routes.rb file you probably have something like resources: posts which covers all your controller actions such as posts/1/ etc. Another thing is to make sure you restart your server when you edit/change your routes.eb file. Hope this is clear enough to understand.

Upvotes: 0

Related Questions