将帖子功能添加到包含Rails的组

时间:2016-09-11 22:16:08

标签: ruby-on-rails

我正在尝试制作群组管理应用程序。所有组和会员功能都有效。这是我拥有的三种模式。

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

  has_many :memberships, dependent: :destroy
  has_many :groups, -> { uniq }, through: :memberships
end
class Membership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end
class Group < ActiveRecord::Base
  validates_presence_of :name, :description

  has_many :memberships, dependent: :destroy
  has_many :users, -> { uniq }, through: :memberships
end

我即将向群组添加帖子模型,以便用户可以在群组中发布状态。但我不确定最好的方法是什么。我只尝试使用成员资格模型,我用has_many和belongs_to方法引用它。但我无法使其发挥作用。

我必须遵循的方式是什么?

这就是我的架构。

ActiveRecord::Schema.define(version: 20160909174120) do

  create_table "groups", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
    t.integer  "owner_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "memberships", force: :cascade do |t|
    t.integer  "group_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    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",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

解决方案

由于会员资格模型已经group_iduser_id,我想通过会员资格使用它们,因为要发布到群组,您必须是会员。

所以,我重新审视了我所做的事情并最终使其发挥作用。

rails g model Post status:text membership_id:integer
rake db:migrate
class Post < ActiveRecord::Base
  belongs_to :membership
end
class Membership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user

  has_many :posts
end

1 个答案:

答案 0 :(得分:0)

Rails g model Post status:text

-

Rake db:migrate

-

class Post < ActiveRecord::Base
 belongs_to :user
 belongs_to :group
end

-

class User < ActiveRecord::Base
 has_many :posts
end

-

class Group < ActiveRecord::Base
 has_many :posts
end

这就是我要做的事。