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.