Rails model attr_accessor attribute not saving?

风格不统一 提交于 2019-12-10 11:33:50

问题


Here is the structure I'm working with:

app/models/model.rb

class Model < ActiveRecord::Base
    attr_accessor :some_var
end

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

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/12905103/rails-model-attr-accessor-attribute-not-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!