Rails:表上的belongs_to列

时间:2012-04-23 02:49:19

标签: ruby-on-rails-3 facebook-graph-api

我正在查看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

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

此外,在模型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

的链接

Facebook.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

1 个答案:

答案 0 :(得分:0)

您在一个问题中有很多问题,关于belongs_to的问题,您可以在这里找到答案:t.belongs_to in migration