Search code examples
ruby-on-rails-4class-variables

Accessing class variables in views


What is the correct syntax for storing something in my class variable from a view ? Let's say that this is the code:

Controller:

class FooController < ApplicationController
@@myvar = "I'm a string"

*
*
*
methods
*
*
*
end

Form:

<%= form_for(@something) do |f| %>
    <%= f.text_field :myvar %>
    <%= f.submit %>
<% end %>

This is just an example of a form as it is not functional, I cannot find what the correct syntax is for accesssing @@myvar from the view. Thanks !


Solution

  • as on request i edited, including attr_accessor

    Rails way. Ill just fly over, hope you get it. you defenitely need to read more introductions to rails and its concept.

    you have a rails-model, lets call it Animal

    class Animal < ActiveRecord::Base
      attr_accessor :non_saved_variable
    
    end
    

    this is having a database-table, lets say in this table we store race, name and age.

    now we need a controller, to create/edit/update/delete animals

    class AnimalController < ActionController::Base
       def new
         # this creates a new animal with blank values
         @animal = Animal.new
       end
    end
    

    now you need to go into your routes.rb and create a route for animals

    resources :animal
    

    this will create all (restful) routes for every actions of an animal.

    now you need to have your template to render a form

    form_for is a rails helper, to create a form, associated with the @animal (which is a new Animal). You pass |f| into the block, so with f you can access the form

    =form_for @animal do |f|
    

    then you can go for each field you need to call another rails helper you can also access attr_accessors.

    =f.text_field :race
    =f.text_field :name
    =f.text_field :age
    =f.text_field :non_saved_variable
    

    by that you get the stuff

    dont fortget f.submit because your form needs a submit button

    if you now click on your button, the form will be posted to the create method of rails. so you need to bring it into your controller

    def create
       # create a new animal with the values sended by the form
       @animal = Animal.new params[:animal]
    
       # here you can access the attr_accessor
       @animal.do_something if @animal.non_saved_variable == "1337"
    
       if @animal.save
         # your animal was saved. you can now redirect or do whatever you want
       else
         #couldnt be saved, maybe validations have been wrong
         #render the same form again
         render action: :new
       end
    end
    

    i hope that gave you a first insight of rails ?!