0

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.

1
  • 1
    did you try self.status = 'foo' ? Commented Feb 5, 2011 at 18:12

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, be aware that your validations will not happen with update_attribute; if you want your validations to run (and you probably do), use update_attributes, with the "s". Check it out.
0

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.

2 Comments

This was nearly 3 years ago, I don't need help with it anymore.
I have added that if someone can get help form this snippet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.