0

I'm using Rails 3.2.11 and Ruby 1.9.3 in Mac OS X Mountain Lion

I have a user model, and i created a virtual attribute called message

attr_accessor :message

In my code, i try this:

if condition == true
  self.message = "Value is True."
else
  self.message = "Value is not True"

In my controller, I try this

def method
  user = User.find(1)
  flash[:message] = user.message
end

But the flash message doesn't display anything. It's nil. How can I pass the value I set in the model to the controller? thanks a lot!

4

1 回答 1

3

似乎是逻辑:当您从数据库中检索对象时,没有理由它的 attr_accessor 应该包含任何内容。

坚持你的逻辑,你宁愿:

  • 删除 attr_accessor

  • 在您的 User 类中创建一个方法。

像这样:

def message 
  if condition
    "Value is True."
  else
    "Value is not True"
  end
end

请注意,您正在耦合数据和视图,这不是一个好习惯。

于 2013-04-18T10:24:50.797 回答