无法通过关联创建has_many,如何填充表?

时间:2017-04-17 08:25:09

标签: ruby-on-rails sqlite activerecord

我正在使用rails 5创建一个Web应用程序,用户可以在其中创建组并将文件上传到组。我创建了一个用户模型,分组模型和成员模型。

class User < ApplicationRecord

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
     devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable


    groupify :group_member
    groupify :named_group_member

    validates :email, :presence => true, :uniqueness => true
    has_many :members
    has_many :groups, through: :member
end

class Group < ApplicationRecord
    groupify :group, members: [:users, :assignments], default_members: :users

    has_many :members
    has_many :groups, through: :member
end

class Member < ApplicationRecord
    belongs_to :group
    belongs_to :user
end

我可以创建用户和组,但我无法理解如何填充成员表。它由2列组成,user_id和group_id。

编辑:  这些是我的迁移文件

class CreateMembers < ActiveRecord::Migration[5.0]
  def change
    create_table :members do |t|
      t.integer :user_id
      t.integer :group_id

      t.timestamps
    end
    add_index :members , [:user_id,:group_id]
  end
end
class DeviseCreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :name ,              null: false
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      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.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
  end
end

我的users表中没有group_id,它只在group和member table中。

2 个答案:

答案 0 :(得分:0)

有两种方式。

1)创建会员

Member.create(user_id: user_id, group_id: group_id)

2)在User.groups_ids

添加组ID
ids = user.groups_ids
ids.push(group_id)
user.groups_ids = ids

答案 1 :(得分:0)

通过应该是复数