Ruby Rails 4:如何实现一个模型关联,用户可以通过该模型注册(订阅)其他用户的帖子

Ruby Rails 4:如何实现一个模型关联,用户可以通过该模型注册(订阅)其他用户的帖子,ruby,activerecord,ruby-on-rails-4,has-many-through,has-many,Ruby,Activerecord,Ruby On Rails 4,Has Many Through,Has Many,我正在建立一个网站,在那里用户可以为编程课程和学校项目创建编程想法。他们可以查看所有创意,并注册(订阅)其他用户创建的创意。“注册”按钮将位于用户想法的“显示”页面上 我曾尝试创建一个relationshipsmodel,它的行为类似于联接表,但没有成功。然后,我的老师告诉我,我可以通过关联创建has_many,而无需创建一个专用的关系表来通过注册连接用户和想法模型 我是rails的新手,刚刚完成了Michael Heartl的rails教程 这是我的代码: class User < Ac

我正在建立一个网站,在那里用户可以为编程课程和学校项目创建编程想法。他们可以查看所有创意,并注册(订阅)其他用户创建的创意。“注册”按钮将位于用户想法的“显示”页面上

我曾尝试创建一个relationshipsmodel,它的行为类似于联接表,但没有成功。然后,我的老师告诉我,我可以通过关联创建has_many,而无需创建一个专用的关系表来通过注册连接用户和想法模型

我是rails的新手,刚刚完成了Michael Heartl的rails教程

这是我的代码:

class User < ActiveRecord::Base
  has_many :ideas
  has_many :enrolled_ideas, through: :enrollments, dependent: :destroy, class_name: "Idea"

class Idea < ActiveRecord::Base
    belongs_to :user

WebappProject::Application.routes.draw do
  resources :users 
  resources :sessions,   only: [:new, :create, :destroy]
  resources :ideas do
    member do
      get :enrolled
    end
  end
class用户

这些想法在主页(静态页面控制器)上,用户可以点击。然后,他通过show action被发送到和idea(ideas\U控制器)的show页面。在这个页面上(来自用户的特定想法),我想要一个“注册”按钮。因此,如果用户点击它,创意的所有者可以在他的用户展示页面上列出所有注册的用户。

有两种方法可以实现,它们都属于Rails中的许多(HABTM)表,都使用中间表。你老师的意思可能是,有一种方法可以在不添加第三个模型的情况下实现HABTM关系。这样您就可以:

class User < ActiveRecord::Base
  has_and_belongs_to_many :ideas
end

class Idea < ActiveRecord::Base
  has_and_belongs_to_many :users
end
class用户
这样你就可以跑了

User.first.ideas #to get all the ideas a user created or is subcribed to
Idea.first.users #to get all the users subscribed to an idea
Idea.first.users << User.first # to subscribe the first user to the first idea
User.first.ideas#获取用户创建或订阅的所有想法
Idea.first.users#让所有用户订阅一个Idea

想法。首先。用户啊,谢谢!!,我选择了第二个选项,并创建了一个单独的订阅表。在用户方面,我选择了“has_many:subscribed_by,through::subscriptions,source::user”,这样现在我就可以检索所有订阅帖子的用户。
class CreateUsersIdeas < ActiveRecord::Migration
  def change
    create_table :users_ideas do |t|
      t.belongs_to :user
      t.belongs_to :idea
    end
  end
end
class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :ideas, through: :subscriptions
end

class Subscriptions < ActiveRecord::Base
  belongs_to :user
  belongs_to :idea
end

class Idea < ActiveRecord::Base
  has_many :subscriptions
  has_many :users, through: :subscriptions
end