简体   繁体   English

Rails模型attr_accessor属性不保存?

[英]Rails model attr_accessor attribute not saving?

Here is the structure I'm working with: 这是我正在使用的结构:

app/models/model.rb 应用程序/模型/ model.rb

class Model < ActiveRecord::Base
    attr_accessor :some_var
end

app/models/model_controller.rb 应用程序/模型/ 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

Whenever I run this code (eg the show method), the if clause is evaluated to be true (eg @model.some_var == nil). 每当我运行此代码(例如show方法)时,if子句被评估为true(例如@ model.some_var == nil)。 How do I get around this? 我该如何解决这个问题? Is there something wrong in my assumption of how attr_accessor works? 我对attr_accessor的工作方式有什么不妥吗?

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. attr_accessor是一个内置的Ruby宏,它将为对象的实例变量定义一个setter和一个getter,并且与ActiveRecord实例的数据库列没有任何关系。 For example: 例如:

class Animal
  attr_accessor :legs
end

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

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. 然后ActiveRecord将自动创建访问器方法,您可以(应该)删除您的attr_accessor声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM