Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Is Array constants in the model can be changed during runtime?

Model Array

  • Please log in to reply
1 reply to this topic

#1 CJRoman

CJRoman

    Passenger

  • Members
  • 1 posts

Posted 03 February 2014 - 05:31 AM

Hello everyone!

 

I have strange problem. Here is the code: 

 

model: 

 

class ItServiceJob < ActiveRecord::Base
TYPES = [["Important", 0], ["Not important", 1], ["SERGEY", 2]]

belongs_to :user
end

view (haml): 

 

  %div{:role => "main", :class => "ui-content"}
    - job_types = ItServiceJob::TYPES
    - job_types.pop if (!can?(:manage, :it_service) || !can?(:born, :sergey))
    = job_types
    = form_for ItServiceJob.new, url: "#" do |f|
      
      %p
        = f.label :type
        = f.select :type, job_types

Now, when I refresh the page every time, the array pops one by one item and finally get empty! But, why? Why the constant changes, not variable? What I'm doing wrong?



#2 Lauree

Lauree

    Passenger

  • Members
  • 6 posts
  • LocationNew York

Posted 09 May 2014 - 11:21 AM

Hi CJRoman,

 

When you are writing job_types = ItServiceJob::TYPES that means you actually giving another reference job_types to the array referred by ItServiceJob::TYPES constant.

 

In that case when you are updating job_types the array referred by ItServiceJob::TYPES will also be updating as job_types and ItServiceJob::TYPES are now referring to same array.

 

You can use Array.new as followed for creating a new array with the same elements as ItServiceJob::TYPES:

- job_types = Array.new(ItServiceJob::TYPES)

Thanks,

Lauree


Hire skilled Ruby on Rails Developer

Check out Ruby on Rails Outsourcing Services by Allerin






Also tagged with one or more of these keywords: Model, Array

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users