Explanation of @ variables inside Rails models

I worked through several Rails applications that use @attribute variables (which are already attr_accessible) in models. It was difficult for me to get information about this, but from what I am collecting nameand @nameit is the same in the model, but I am probably mistaken about it.

How do these @ variables work and why use @ symbol variables?

+4
source share
6 answers

To add to the current answers, @instance_variablesfrom object-oriented programming ...

object-oriented programming , instance variable - , (.. -), .


OOP

"" - strings, integers .. .

() ( classes). , , , ...

#app/models/product.rb
class Product < ActiveRecord::Base
  #-> class
end

def new
   @product = Product.new #-> creating a new instance of the class
end

Ruby/Rails ; , . : :

enter image description here

- / ( Product), .

, . , :

@product = Product.new
@product.save

-

class:

# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    @product = Product.new #-> @product only available within ProductsController
  end
end

Rails classes, :

Request > Rack > Routes > ProductsController.new(request).show > Response

, @instance_variable , instance...

# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    @product = Product.new
    product_save
  end

  private

  def product_save
    @product.save #-> @product available in instance of ProductsController class
  end
end

@instance_variables / , . ( Product) stock:

#app/models/product.rb
class Product < ActiveRecord::Base
  def stock
     @qty / @orders
  end
end

getter/setter Ruby, , :

@product = Product.find x
@product.stock #-> outputs stock value for that product
+3

"@" , , ruby. (@) ().

, @book, Book ( ). , @book, , , .

, .


+3

, @, , , . ,

class Something
  def a_method(name)
    @i_variable = name
    normal_variable = "hey"
  end

  def another_method
    @i_variable.reverse #can be seen here and used
    normal_variable  #cannot be seen here and cannot be used, throws an error
  end
end

Rails , , Model, View, Controller .

+2

, @, . , . , :

class Dog 
    def initialize(name, breed)
        @name = name
        @breed = breed
    end 
end 

, Dog, .

fido = Dog.new("Fido", "Dalmation")

name breed, fido.

fido.name => "Fido"

fido.breed => "Dalmation" 
+2

:

def foo
  thing = "value"
end

foo
puts thing

NameError: undefined local variable or method `thing' for main:Object

:

def foo
  @thing = "value"
end

foo
puts @thing

""

, @variables , , .

@variables , :

def hello
  @current_user_name = User.find(params[:user_id]).name
end
# and in the view:
Hello, <%= @current_user_name %>

, @, , .

+1

var @ . Var @- .

A variable with @ can be accessed at the object level if the object has a method that returns a value or sets a value for it: attr_accessor, attr_reader or def.

0
source

Source: https://habr.com/ru/post/1628206/


All Articles