Ruby - Difference between :variable and @variable

后端 未结 1 1005
予麋鹿
予麋鹿 2021-02-06 14:48

As a Ruby on Rails newbie, I understand that the \"@\" and \":\" references have different meanings. I saw this post in SO, which described some of the differences.

1条回答
  •  囚心锁ツ
    2021-02-06 14:58

    Is my understanding of the difference between :my_selections and @my_selections correct?

    Nope :(

    : indicates a symbol, its not an alias for anything intrinsically. It's like an immutable string, which is often used as a name to represent something.

    In places where the Rails api accepts a symbol in place of an instance variable, internally it's actually doing this:

    self.instance_variable_get "@#{my_symbol}"
    

    Which actually returns the value of the requested instance variable.

    So the only reason that you think symbol correspond to instance variable at all, is because the code that drives the API you are using works that way. Without a framework to do that for you, there is no correlation at all.

    Why would switching to :my_selection resolve my original error?

    for_form(model_instance) will generate a form that submits to the create action if the model instance is unsaved, or to the update action if the model is already exiting in your DB.

    No I don't know what's in @my_selection, but whatever class it is doesn't seem to be generating the routes properly.

    resources :my_selections
    

    Will generate a route you would invoke like this:

    my_selections_path
    

    How your form is generating a route for my_selection_index_path I'm not sure and it really depends on what your models are.

    And when you pass a symbol instead, and there is no corresponding ivar, it uses that as the model name for route generation. Which would do the right thing by trying to invoke my_selections_path, which is directly based on the symbol you pass in.

    0 讨论(0)
提交回复
热议问题