活跃记录协会一对多

时间:2013-12-07 20:12:21

标签: mysql ruby-on-rails rails-activerecord

我对目前的活动记录协会有疑问。

我正在制作一个基于问题的评论系统(非常类似于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

以下是我的Active Record Association:

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后端

1 个答案:

答案 0 :(得分:1)

不,相关记录的user_id字段只有在您创建 关联时才会“自动”填写,如:

user.comments << Comment.create(...)

有关其他选项,请参阅http://guides.rubyonrails.org/association_basics.html#has-many-association-reference。当然,您也可以手动设置user_id