![](/img/trans.png)
[英]Rails / Active Record has_many through association - fetching a record
[英]Active Record Association one to many
我对当前的活动记录协会有疑问。
我正在基于一个问题创建一个评论系统(非常类似于stackoverflow)。
我正在查看该关联,并且一个用户有很多评论,一个评论属于一个用户。
现在,当我进行实际评论时,因为要建立关联,所以user_id应该包含在评论的user_id字段中,对吗?
这是我的架构:
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.integer "question_id", limit: 255
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "provider"
t.string "uid"
t.string "name"
end
create_table "comments", force: true do |t|
t.integer "user_id" **THIS IS WHERE I AM EXPECTING A JOIN AND WHEN A USER MAKES A COMMENT TO HAVE THE USER_ID NUMBER STORED HERE
t.integer "question_id"
t.text "comment"
t.integer "upvotes"
t.datetime "created_at"
t.datetime "updated_at"
end
这是我的活动记录关联:
USER.RB:
class User < ActiveRecord::Base
has_many :questions
has_many :comments
has_many :votes
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
# user.username = auth.info.nickname
user.email = auth.info.email
user.name = auth.info.name
end
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], without_protection: true) do |user|
user.attributes = params
user.valid?
end
else
super
end
end
def password_required?
super && provider.blank?
end
def update_with_password(params, *options)
if encrypted_password.blank?
update_attributes(params, *options)
else
super
end
end
end
Comment.rb:
class Comment < ActiveRecord::Base
belongs_to :question
belongs_to :user
has_many :votes
end
我的最终目标是让我的评论架构在做出新评论时注册user_id,从而将评论与用户相关联。
现在,我的user_id为“ nil”
**这是Backbone前端上的Rails后端
不,如果通过关联创建关联记录的user_id
字段,则只能“自动”填写,例如:
user.comments << Comment.create(...)
有关其他选项,请参见http://guides.rubyonrails.org/association_basics.html#has-many-association-reference 。 当然,您也可以手动设置user_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.