Rails模型的attr_accessor属性无法保存? [英] Rails model attr_accessor attribute not saving?

查看:83
本文介绍了Rails模型的attr_accessor属性无法保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的结构:

Here is the structure I'm working with:

app/models/model.rb

app/models/model.rb

class Model < ActiveRecord::Base
    attr_accessor :some_var
end

app/models/model_controller.rb

app/models/model_controller.rb

class ModelsController < ApplicationController
    def show
        @model = Model.find(params[:id])
        @other_var
        if @model.some_var.nil?
            @model.some_var = "some value"
            @other_var = "some value"
        else
            @other_var = @model.some_var
        end
    end
end

每当我运行此代码(例如show方法)时,if子句就被评估为true(例如@ model.some_var == nil).我该如何解决?我对attr_accessor的工作原理有误吗?

Whenever I run this code (e.g. the show method), the if clause is evaluated to be true (e.g. @model.some_var == nil). How do I get around this? Is there something wrong in my assumption of how attr_accessor works?

推荐答案

attr_accessor是一个内置的Ruby宏,它将为对象的实例变量定义一个setter和getter,并且没有任何要处理的内容.使用ActiveRecord实例处理数据库列.例如:

attr_accessor is a built-in Ruby macro which will define a setter and a getter for an instance variable of an object, and doesn't have anything to do with database columns with ActiveRecord instances. For example:

class Animal
  attr_accessor :legs
end

a = Animal.new
a.legs = 4
a.legs #=> 4

如果要将其保存到数据库,则需要在迁移中定义一列.然后ActiveRecord将自动创建访问器方法,您可以(应该)删除您的attr_accessor声明.

If you want it to be saved to the database, you need to define a column in a migration. Then ActiveRecord will create the accessor methods automatically, and you can (should) remove your attr_accessor declaration.

这篇关于Rails模型的attr_accessor属性无法保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆