0

I'm a newbie so apologies if this is basic but it's been driving me crazy. I have two Rails models called user.rb and question.rb. A user can ask multiple questions and a question can only belong to one user. For authentication, I am using Omniauth-Facebook. Here are the models:

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

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

I have a form where a user can create a question. What I would like to do is, on submitting the form, associate question with user who created it by assigning user_id attribute.

I have an object in my application controller for defining the current_user (I use 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

What's the best way to do this?

My environment: Rails 3.2.8, Ruby 1.9.3-p195, using omniauth-facebook but not Devise.

4

1 回答 1

0

这是您的应用程序控制器中的一个方法,有望检索当前用户:

def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

因此,您可以在 QuestionsController 的 new 或 create 方法中使用它来设置用户,如下所示:

@question.user = current_user

这应该够了吧。您还可以使用 before_save 回调。

于 2012-10-06T13:09:52.927 回答