ActiveRecord Virtual Attributes treaded as a record attributes

前端 未结 6 1487
小鲜肉
小鲜肉 2021-01-02 04:54

I am running into a problem with to_json not rendering my virtual attributes

class Location < ActiveRecord::Base
    belongs_to :event
    before_create :g         


        
6条回答
  •  孤独总比滥情好
    2021-01-02 05:30

    An old question but what OP asked is now possible and simple once you know how. Here a complete runnable example but everything you need is in the class Location. The attribute statement expands the attributes of the model and the after_initialize takes care of the assignment of the value.

    require 'active_record'  
    
    ActiveRecord::Base.establish_connection(  
      :adapter=> "sqlite3",  
      :database=> ":memory:"  
    )  
    
    ActiveRecord::Schema.define do
      create_table :events do |table|
        table.column :name, :string
      end
      create_table :locations do |table|
        table.column :name, :string
        table.column :event_id, :integer
      end
    end
    
    class Event < ActiveRecord::Base
      has_one :location
    end
    
    class Location < ActiveRecord::Base
      belongs_to :event
      attribute :event_name, :string
    
      after_initialize do
        self.event_name = event.name
      end
    end
    
    Event.create(name: 'Event1')
    Location.create(name: 'Location1', event_id: 1)
    p Model.attribute_names
    p Event.first
    p Event.first.location
    
    #["id", "name", "event_id", "event_name"]
    #
    #
    

提交回复
热议问题