在RoR中使用帖子进行用户组的最佳方式

时间:2014-06-28 17:11:59

标签: ruby-on-rails ruby-on-rails-4

我是一个刚开始使用Rails的开发人员,我构建了一些更简单的应用程序。但是,我是否有一个项目需要我构建一个具有用户和"用户组的Web应用程序"有帖子。

用户应该能够加入群组,然后将帖子发布到群组中。除此之外,我还希望用户能够在"仪表板中看到他们所属的组中的最新帖子" "流速" (像facebook流程)。我想知道在这种情况下关系应该如何?

我已经读过,has_many_through是一种构建属于群组的用户的好方法,但是我应该如何建立关系以便群组也有帖子呢?

2 个答案:

答案 0 :(得分:0)

在我看来,这可能是一个好方法:

def User < ActiveRecord::Base
    has_many :groups, through: :membership
    has_many :posts
end

def Membership < ActiveRecord::Base
    has_one :user
    belongs_to :group
end

def Group < ActiveRecord::Base
    has_many :users, through: :membership
    has_many :posts
end

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

答案 1 :(得分:0)

如果用户正在创建帖子,那么将帖子属于用户是有意义的。但是用户在一个组中发帖,因此帖子也可以属于一个组。

因此,每个用户has_many发帖,每个群组has_many也会发布。

要最初(通过联接表)链接用户和群组,您可以使用has_many_and_belongs_to关系。

迁移

用户

运行rails g model User name:string以生成迁移:

#create_users
class CreateUsers < ActiveRecord::Migration
    def change
        create_table :users do |t|
            t.string :name
            <other fields...>
            t.timestamps
        end
    end
 end

和基本模型:

class User < ActiveRecord::Base
end

运行rails g model Group name:string以生成迁移:

#create_groups
class CreateGroups < ActiveRecord::Migration
    def change
        create_table :groups do |t|
            t.string :name
            <other fields...>
            t.timestamps
        end
    end
 end

和基本模型:

class Group < ActiveRecord::Base
end

加入表

最初链接用户和群组(会员资格表)......

运行rails g migration CreateJoinTableUserGroup user group以生成:

class CreateJoinTableUserGroup < ActiveRecord::Migration
    def change
        create_join_table :users, :groups
    end
end

帖子

继续创建一个posts表:rails g migration CreatePosts。并将迁移更改为:

class CreatePosts < ActiveRecord::Migration
    def change
        create_table :posts do |t|
            t.string :text
            t.belongs_to :user
            t.belongs_to :group

            <other fields...>
            t.timestamps
        end
    end
 end

此时,您需要运行rake db:migrate

模特

这是我为模特做的事情:

class User < ActiveRecord::Base
    has_many :posts
    has_and_belongs_to_many :groups, :join_table => :groups_users
end
class Group < ActiveRecord::Base
    has_many :posts
    has_and_belongs_to_many :users, :join_table => :groups_users
end
class Post < ActiveRecord::Base
    belongs_to :user
    belongs_to :group
end

希望有所帮助!

相关问题