Problem with setting attributes

I have an ActiveRecords element and am trying to set a default value ("Test item") for each of them using a block.
In this expression:

 list = {"type1", "type2", "type3", "type4", "..."} list.each { |name| @item.attributes["#{name}"] = "Test item"] } 

values ​​not set.

I have to use @item.attributes["#{name}"] for interpolation because I cannot do this for each item:

 @item.tipe1 = "Test item" 

So what happens in the first statement? What for? If what I would like to do is not possible in this way, how can I do the same?

+4
source share
3 answers

The purpose of @items.attributes["#{name}"] = "Test item"] does not work, because the attributes method returns a new Hash object every time you call it. This way you are not changing the value of the @items ' object as you thought. Instead, you change the value of the new hash that was returned. And this hash is lost after each iteration (and, of course, when each block is completed).

A possible solution would be to create a new hash with the @items attribute @items and assign it using the attributes= method.

 h = Hash.new # this creates a new hash object based on @items.attributes # with all values set to "Test Item" @items.attributes.each { |key, value| h[key] = "Test Item" } @items.attributes = h 
+2
source

You can use the submit method for this purpose. Perhaps like this:

 list = {"type1", "type2", "type3", "type4", "..."} list.each { |name| @item.send("#{name}=", "Test item") } 
+2
source

I think the problem is that you only change the hash of the returned attribute, not the ActiveRecord object.

You need to do something like:

 # make hash h @items.attributes = h 

Following your example, perhaps something like:

 @items.attributes = %w{type1 type2 type3 type4}.inject({}) { |m, e| m[e] = 'Test item'; m } 

BTW, "#{e}" is the same as a String e expression or for any type: e.to_s . The second example may be easier to read:

 a = %w{type1 type2 type3 type4} h = {} a.each { |name| h[name] = 'test item' } @items.attributes = h 

Using the attributes= method is probably intended for hash constants, for example:

 @items.attributes = { :field => 'value', :anotherfield => 'value' } 

For fully created attributes, you can take the DanneManne clause and use send.

+1
source

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


All Articles