ruby - Rails - Controller Object Scope vs Controller Function Scope -


i have seen local variables object variables being used in rails controller actions. example of both given below:

# local variable class mycontroller < applicationcontroller   def some_action     local_variable = model.find(<some-condition>).delete   end end  # object variable class mycontroller < applicationcontroller   def some_action     @object_variable = model.find(<some-condition>).delete   end end 

i want know difference between both of them , scenarios both suited used in.

rails exports controller's instance variables called view context:

class usercontroller < applicationcontroller   def new      @user = user.new   end end 

# view gets @ variables controller. # views/users/new.html.haml = form_for(@user) 

rails offers mechanism called locals well:

class usercontroller < applicationcontroller   def new      render :new, locals: { user: user.new }   end end 

# locals lexical variables in view context. # views/users/new.html.haml = form_for(user) 

which exports local variable view context.

so when use what?

use lexical (local) variables (some_variable) not want implicitly export view. use locals option when rendering when need pass data between views , partials or things not quite part of "public api" of controller.

use instance variables (@foo) important exports controller , treat them part of public api. make sure test them:

describe usercontroller   describe "#new"     before { :new }     "assigns new user @user"       expect(assigns(:user)).to be_a_new_record     end   end end 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -