Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update value of a Model's attribute

I have an database items and two items in it. They have column named "popularity", that I set to 0.

class Item < ActiveRecord::Base
  attr_accessible .. :popularity, ..

  before_create :default_values
  def default_values
    if self.popularity.nil? == true || self.popularity.blank? == true || self.popularity.class != Integer
      self.popularity = 0
    end
  end

How to change this value via code\console and save it? I tried

  Item.find(1).popularity = 1
  Item.save

But it didn't save my val. Whats wrong?

like image 453
AKovtunov Avatar asked Sep 08 '12 09:09

AKovtunov


People also ask

What happens if no value is specified in @modelattribute?

If no 'value' is specified in @ModelAttribute then the returned type is used as the attribute name. This annotation is used to populated common model attributes for multiple request handlers.

What is @modelattribute and how to use it?

As the introductory paragraph revealed, @ModelAttribute can be used either as a method parameter or at the method level. When the annotation is used at the method level it indicates the purpose of that method is to add one or more model attributes.

How to replace values in a newly created attribute?

This one will do the replacement of the values in the newly created attribute. By using the Arcade code expression right at the bottom. This uses the creation of a variable and a conditional "if" statement to find and replace values accordingly.

What is @modelattribute in Spring MVC?

Overview One of the most important Spring-MVC annotations is the @ModelAttribute annotation. The @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view.


1 Answers

here is the solution

item = Item.find(1)
item.popularity = 1
item.save
like image 128
abhas Avatar answered Sep 21 '22 23:09

abhas