【发布时间】:2012-10-06 12:31:48
【问题描述】:
我是新手,如果这是基本的,我很抱歉,但这让我发疯了。我有两个名为 user.rb 和 question.rb 的 Rails 模型。一个用户可以提出多个问题,一个问题只能属于一个用户。对于身份验证,我使用的是 Omniauth-Facebook。以下是模型:
用户.rb
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# provider :string(255)
# uid :string(255)
# name :string(255)
# oauth_token :string(255)
# oauth_expires_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# email :string(255)
# fbprofileimage :text
#
class User < ActiveRecord::Base
attr_accessible :provider, :uid, :email, :fbprofileimage, :name
has_many :questions, :dependent => :destroy
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.fbprofileimage = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end
问题.rb
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# headline :string(255)
# description :text
# user_id :integer
# budget :decimal(, )
# star :binary
# old_star :binary
# created_at :datetime not null
# updated_at :datetime not null
#
class Question < ActiveRecord::Base
attr_accessible :budget, :description, :headline, :star, :old_star, :user_id, :updated_at, :created_at
belongs_to :user
validates :headline, :description, :presence => true
end
我有一个表单,用户可以在其中创建问题。我想做的是,在提交表单时,通过分配 user_id 属性将问题与创建它的用户相关联。
我的应用程序控制器中有一个对象用于定义 current_user(我使用omniauth):
class ApplicationController < ActionController::Base
protect_from_forgery
after_save :update
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
最好的方法是什么?
我的环境:Rails 3.2.8,Ruby 1.9.3-p195,使用omniauth-facebook,但不使用Devise。
【问题讨论】:
标签: ruby-on-rails activerecord attributes