Ruby on rails Rails—表单提交时将属性中的记录从一个表复制到另一个表的语法
我是一个新手,所以如果这是基本的道歉,但这已经让我发疯了。我有两个Rails模型,分别是user.rb和question.rb。一个用户可以问多个问题,而一个问题只能属于一个用户。对于身份验证,我使用Omniauth Facebook。以下是模型: user.rbRuby on rails Rails—表单提交时将属性中的记录从一个表复制到另一个表的语法,ruby-on-rails,activerecord,attributes,Ruby On Rails,Activerecord,Attributes,我是一个新手,所以如果这是基本的道歉,但这已经让我发疯了。我有两个Rails模型,分别是user.rb和question.rb。一个用户可以问多个问题,而一个问题只能属于一个用户。对于身份验证,我使用Omniauth Facebook。以下是模型: user.rb # == Schema Information # # Table name: users # # id :integer not null, primary key # provid
# == 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
#==架构信息
#
#表名:用户
#
#id:整数不为空,主键
#提供程序:字符串(255)
#uid:string(255)
#名称:字符串(255)
#oauth_令牌:字符串(255)
#oauth在:datetime到期
#创建时间:datetime非空
#更新时间:datetime非空
#电子邮件:string(255)
#fbprofileimage:文本
#
类用户:破坏
定义自授权(授权)
其中(auth.slice(:provider,:uid)).first_或_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\u expires\u at=Time.at(auth.credentials.expires\u at)
user.save!
结束
结束
结束
问题.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
#==架构信息
#
#表名:问题
#
#id:整数不为空,主键
#标题:字符串(255)
#说明:文本
#用户id:integer
#预算:十进制(,)
#星:双星
#旧恒星:双星
#创建时间:datetime非空
#更新时间:datetime非空
#
类问题true
结束
我有一个表单,用户可以在其中创建一个问题。我想做的是,在提交表单时,通过分配user_id属性将问题与创建它的用户关联起来
我的应用程序控制器中有一个对象,用于定义当前用户(我使用omniauth):
class ApplicationController
最好的方法是什么
我的环境:Rails 3.2.8,Ruby 1.9.3-p195,使用omniauth facebook,但不使用Desive。这是应用程序控制器中的一种方法,希望检索当前用户:
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
因此,您可以在QuestionsController的new或create方法中使用它
要按如下方式设置用户:
@question.user = current_user
这应该能奏效。您还可以使用“保存前”回调
@question.user = current_user