【问题标题】:Rails model is not setting attributeRails 模型未设置属性
【发布时间】:2013-04-16 18:49:40
【问题描述】:

我是 Rails 开发的新手

Rails 3.2.13 / 红宝石 1.9.3

我有这个模型

class Post < ActiveRecord::Base
    attr_accessible :content, :title
    attr_accessor :testing

    def asignar
        title = "hey"
    end
end

然后当我进入 rails 控制台时:

irb(main):004:0* post = Post.new
=> #<Post id: nil, title: nil, content: nil, created_at: nil, updated_at: nil>
irb(main):005:0> post.asignar
=> "hey"
irb(main):006:0> post.title
=> nil

这正常吗?我是不是必须一直保存对象才能获取属性?

【问题讨论】:

  • self.title = 'hey'; title = "hey" 设置的是局部变量 title,而不是属性。
  • 正如 Lee 所说,在写入模型的属性时,您应该使用 self.title。读取属性时通常只使用属性名称title,但self.titleself[:title] 也可以。
  • Lee Jarvis 这正是答案,我知道这很愚蠢,但我仍然认为这可能对其他人有用,为什么不将您的评论作为答案,以便我可以将其标记为已接受 :)谢谢
  • 看起来 hyngyn 先到了。他的回答也是正确的,不过谢谢!

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 ruby-1.9.3


【解决方案1】:

试试这个:

def asignar
    self.title = "hey"
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多