0

在我的应用程序中,我有用户和项目的模型。

我希望用户能够关注许多项目。因此,用户拥有_许多项目,并且项目属于_不仅创建它们的用户,而且还有关注它们的用户。

所以我生成了一个名为的迁移ProjectRelationship并试图让它在下面流动,但它似乎不起作用。有人可以帮我修复我的关联吗?

谢谢您的帮助!

project_relationship.rb

class ProjectRelationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

项目.rb

belongs_to :user
has_many :project_relationships
has_many :followers, through: :project_relationships, source: :user

用户.rb

has_many :projects
has_many :project_relationships
has_many :projects_followed, through: :project_relationships, source: :project

架构.rb

create_table "project_relationships", :force => true do |t|
  t.integer  "follower_id"
  t.datetime "created_at",     :null => false
  t.datetime "updated_at",     :null => false
  t.integer  "projectuser_id"
end

add_index "project_relationships", ["follower_id"], :name => "index_project_relationships_on_follower_id", :unique => true
add_index "project_relationships", ["projectuser_id"], :name => "index_project_relationships_on_projectuser_id"

项目/show.html.erb

<%= @project.followers.count %>
4

2 回答 2

0

您需要指定外键。ProjectRelationship 模型将期望相应的表具有“user_id”和“project_id”列。但是,您使用了不同的名称。所以要么指定外键:

class ProjectRelationship < ActiveRecord::Base
  belongs_to :user, foreign_key: "follower_id"
  belongs_to :project, foreign_key: "projectuser_id"
end

或更改迁移中的列名:

create_table :project_relationships do |t|
  t.integer :user_id
  t.integer :project_id
  ...
end

您还需要在其他模型中指定外键:

class Project < ActiveRecord::Base
  belongs_to :user
  has_many :project_relationships, foreign_key: "projectuser_id"
  has_many :followers, through: :project_relationships, source: :user
end

class User < ActiveRecord::Base
  has_many :projects
  has_many :project_relationships, foreign_key: "follower_id"
  has_many :projects_followed, through: :project_relationships, source: :project
end
于 2013-04-20T03:56:13.990 回答
0

@roma149 - 感谢您的回复。我更新了控制器、路线和你所说的。不会产生错误,但是当我单击 _follow.html.erb 中的按钮跟随时,它似乎没有跟随项目或更新计数“@project.followers.count”

将详细信息移至此处:为什么我的用户关注/取消关注按钮不起作用?

于 2013-04-21T01:27:28.227 回答