0
posts_controller.rb
    class PostsController < ApplicationController
      def new
        @post = Post.new
      end
    end


_form.html.erb
<%= form_with(model: post, local: true) do |form| %>
  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
<% end %>

Above is my code. Why is an instantiation of the class Post as @post in the controller can be accessed as a local variable in the view as post? Hoping I could get an answer from this concern.

1
  • Hey! You've missed an important path in your question: the new.html.erb view file. It should have a code construction similar to render partial: "form", locals: { post: @post }, which passes the local variable to the underlying view _form.html.erb. Take a look at this documentation for the more detailed explanation: guides.rubyonrails.org/… Commented Sep 8, 2020 at 21:34

1 Answer 1

1

The post local variable isn't the one defined in the controller action, but the one defined in the view file which renders the partial _form.html.erb.

The variable defined in the controller is an instance variable, while the one used in the partial is a local one.

You can see ActionController::Renderer#render for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.