在我的应用程序中,我有用户和项目的模型。
我希望用户能够关注许多项目。因此,用户拥有多个项目,而项目属于不仅创建了它们的用户,也是跟随它们的用户。
所以我生成了一个名为ProjectRelationship
的迁移,并尝试让它在下面流动,但它似乎不起作用。有人可以帮我修复关联吗?
感谢您的帮助!
project_relationship.rb
class ProjectRelationship < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
project.rb
belongs_to :user
has_many :project_relationships
has_many :followers, through: :project_relationships, source: :user
user.rb
has_many :projects
has_many :project_relationships
has_many :projects_followed, through: :project_relationships, source: :project
schema.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 %>
答案 0 :(得分:0)
您需要指定外键。 ProjectRelationship模型将期望相应的表具有&#34; user_id&#34;和&#34; project_id&#34;列。但是,您使用了不同的名称。所以要么指定外键:
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
答案 1 :(得分:0)
@ roma149 - 感谢您的回复。我更新了控制器,路线和你说的话。没有错误产生,但是当我点击按钮后面的_follow.html.erb时,它似乎没有跟随项目或更新计数&#34; @ project.followers.count&#34;