ruby on rails - Migration for Users Following Posts -
in application, have models users , projects.
i want users have ability follow many projects. users has_many projects, , projects belongs_to users not created them users follow them too.
so generated migration called projectrelationship
, tried make flow below, doesn't seem work. can me fix associations?
thanks help!
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 |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"
projects/show.html.erb
<%= @project.followers.count %>
you need specify foreign keys. projectrelationship model expecting corresponding table have "user_id" , "project_id" columns. however, used different names. either specify foreign keys:
class projectrelationship < activerecord::base belongs_to :user, foreign_key: "follower_id" belongs_to :project, foreign_key: "projectuser_id" end
or change column names in migration:
create_table :project_relationships |t| t.integer :user_id t.integer :project_id ... end
you need specify foreign key in other models:
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
Comments
Post a Comment