0

我正在查看 fb_graph api gem,它在迁移中有一些代码https://github.com/nov/fb_graph_sample/blob/master/db/migrate/20110623075710_create_subscriptions.rb我无法弄清楚,即列类型,它有belongs_to,这不是典型的列类型。

class CreateSubscriptions < ActiveRecord::Migration
  def self.up
    create_table :subscriptions do |t|
      t.belongs_to :facebook
      t.string :object, :fields, :verify_token
      t.text :history_json
      t.timestamps
    end
  end

  def self.down
    drop_table :subscriptions
  end
end

我理解belongs_to has_manyRails 中的关联,因为它们通常被使用,但它们从不需要属于类型的列,而且我不希望数据库接受这种类型的列。

此外,在模型https://github.com/nov/fb_graph_sample/blob/master/app/models/subscription.rb中声明了 belongs_to Facebook,但我不知道数据库列的实际使用方式。谁能解释一下?

class Subscription < ActiveRecord::Base
  belongs_to :facebook

  validates :facebook, :object, :fields, :history_json, :verify_token, :presence => true

  before_validation :setup, :on => :create

  def history
    JSON.parse(self.history_json)
  end

  def history=(history)
    self.history_json = history.to_json
  end

  def subscribe!(callback)
    Facebook.app.subscribe!(
      :object => self.object,
      :fields => self.fields,
      :callback_url => callback,
      :verify_token => self.verify_token
    )
  end

  private

  def setup
    self.verify_token = ActiveSupport::SecureRandom.hex(16)
    self.history = []
  end

end

这是 Facebook.rb 模型的链接https://github.com/nov/fb_graph_sample/blob/master/app/models/facebook.rb

脸书.rb

class Facebook < ActiveRecord::Base
  has_many :subscriptions

  def profile
    @profile ||= FbGraph::User.me(self.access_token).fetch
  end

  class << self
    extend ActiveSupport::Memoizable

    def config
      @config ||= if ENV['fb_client_id'] && ENV['fb_client_secret'] && ENV['fb_scope'] && ENV['fb_canvas_url']
        {
          :client_id     => ENV['fb_client_id'],
          :client_secret => ENV['fb_client_secret'],
          :scope         => ENV['fb_scope'],
          :canvas_url    => ENV['fb_canvas_url']
        }
      else
        YAML.load_file("#{Rails.root}/config/facebook.yml")[Rails.env].symbolize_keys
      end
    rescue Errno::ENOENT => e
      raise StandardError.new("config/facebook.yml could not be loaded.")
    end

    def app
      FbGraph::Application.new config[:client_id], :secret => config[:client_secret]
    end

    def auth(redirect_uri = nil)
      FbGraph::Auth.new config[:client_id], config[:client_secret], :redirect_uri => redirect_uri
    end

    def identify(fb_user)
      _fb_user_ = find_or_initialize_by_identifier(fb_user.identifier.try(:to_s))
      _fb_user_.access_token = fb_user.access_token.access_token
      _fb_user_.save!
      _fb_user_
    end
  end

end
4

1 回答 1

0

你一个问题有很多问题,一个 about belongs_to,你会在这里找到答案:t.belongs_to in migration

于 2012-04-23T07:14:09.183 回答