问题
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