Rails: why am I having problems accessing this member variable in a controller method?

I see a very strange problem with a simple controller method. Either I'm missing something fundamental, or I'm facing an error. My bid is on the first.

I have a Thing model with a ThingController .

A Thing has two variables, name and display , both lines.

ThingController (code below) has a toggle_display method that toggles the display content between "on" and "off" .

The problem is that when I call this action, Rails finds the correct Thing , but @thing.display is zero. When I check the database, the value in the "display" column is correct.

The strange part is that when I uncomment the third line in the code below (i.e. access @thing.name to access @thing.display ), then @thing.display is ok - it's not zero and it has the value that I would expect. It is as if @thing.display correctly initialized after accessing @thing.name .

Any idea why I will see this very strange behavior?

 def toggle_display @thing = Thing.find(params[:id]) # @thing.name if @thing.display @thing.toggle_display_in_model @thing.save end redirect_to things_url end 
+4
source share
1 answer

The problem is that there is already a method in the kernel called "display" that conflicts with ActiveRecord magic.

ActiveRecord defines methods corresponding to the database fields in the method_missing method. Thus, until the search_ method is called, the methods do not actually exist. When you call the name in @thing, the method_missing method is called because there is no name method. However, when you call a mapping (without first calling another method that does not exist), method_missing is not called because the mapping is already defined in the kernel, and this definition is executed. And since the kernel mapping method returns nil, you get zero.

+7
source

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


All Articles