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