开发者

Setting an attribute in a model

开发者 https://www.devze.com 2023-02-08 23:32 出处:网络
So I\'ve got an application which simply takes a number of RSS feeds and stores them in a table. It checks a couple of things in each entry for conditions and then开发者_开发百科 sets an attribute bas

So I've got an application which simply takes a number of RSS feeds and stores them in a table. It checks a couple of things in each entry for conditions and then开发者_开发百科 sets an attribute based on the condition.

if self.value1 > self.value2 then
    :status => 'foo'
else
    :status => 'bar'
end

I'm still a bit of a noob with Ruby/Rails and setting the status is causing an exception but I don't know why.

Any help would be great.


When you say "sets an attribute", I assume that you mean this is another column on the table. If so, this should work:

if self.value1 > self.value2
    update_attribute :status, "foo"
else
    update_attribute :status, "bar"
end

The "rocket" notation (:this => "that") is used when instantiating an object, or when updating more than one attribute (self.update_attributes :animal => "kitten", :sound => "Roar!"). It's the notation that a Hash uses.

You could also just use status = "foo", but that will set the attribute without saving, so you'd also have to call self.save. update_attribute does both in one neat package.


In Rails 4 I have done with the following method:

def update_test
  if self.value1 > self.value2
      self.status="foo"
  else
      self.status= "bar"
  end
end

and added before_update filter in model.

before_update :update_test, :if => :test_changed?

In this method we don't need to call the save or update_attributes this will be done in a single query.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号