Why instance variable in destroy?

Ín Rails 2.0 the scaffold generator (for e.g. a model called "Context")
creates the destroy method like this:

  def destroy
    @context = Context.find(params[:id])
    @context.destroy

    respond_to do |format|
      format.html { redirect_to(contexts_url) }
      format.xml { head :ok }
    end
  end

My question is: Is there any special reason why @context is defined as
an Instance variable and not just a local variable? It is not used in
any views afterwards - the method always redirects to another action. So
would this be equally valid:

  def destroy
    context = Context.find(params[:id])
    context.destroy
    ...

- Carsten

hmm.. good question
I am going to guess that a local (procedure level) variable would not
have access to class instance methods that are needed.

Someone please correct me if that is wrong.

Carsten Gehling wrote:

i don't think it's necessary
maybe it's just convenient for ppl who want to give some last message
like
"the record with the id #{@context.id} was destroyed"

hmm.. good question
I am going to guess that a local (procedure level) variable would not
have access to class instance methods that are needed.

Someone please correct me if that is wrong.

Nope. The only reason why you'd use an instance variable would be if
the view was going to do something with it, or perhaps if you were
going to call some other instance method of your controller that
wanted access.

My guess is that it's just for consistency with show/edit/update
etc... (which do need it for the view)

Fred

Yes, you could use a local variable. However, how would you write a test to ensure that local variable is being populated with the correct type of data? It’s much easier to write a test for an instance variable.

James

James Herdman wrote:

Yes, you could use a local variable. However, how would you write a
test to
ensure that local variable is being populated with the correct type of
data? It's much easier to write a test for an instance variable.

Ahh James... Now that was a clever answer :slight_smile:

Maybe I just shouldn't think so much over this - I know it is
nitpicking, typically me to wonder about such things.

- Carsten

It’s a very good question though. It shows you’re actually thinking about what you’re doing. If you’re just a RoR-robot you’re not going to get anywhere.

Keep asking questions :slight_smile:

James

Yes, you could use a local variable. However, how would you write a test to
ensure that local variable is being populated with the correct type of
data? It's much easier to write a test for an instance variable.

Although given that the action is destroy, the more thorough test
would be to assert the specified record is no longer in the database,
and for that the instance variable is irrelevant.

Fred