我正在构建一个应用程序(在
Michael Hartl’s chapter 11之后),用户可以在其中跟踪由其他用户创建的项目.
我创建了一个ProjectRelationship模型来保存两个组件:用户的follower_id和项目的projectuser_id.外键已经设置好了.
现在,我的_follow_form.html.erb页面呈现“follow”或“unfollow”,具体取决于current_user是否跟随项目.我在下面附上了我的代码.
现在,在每个项目显示页面上生成跟随按钮.单击_follow.html.erb生成的按钮后,它会相应地跟随项目.
但当我按“取消关注”时,我收到一个错误:
NoMethodError in ProjectRelationshipsController#destroy undefined method `unfollow_project!' for #<User:0x007f9ed83dd6b8> Application Trace | Framework Trace | Full Trace app/controllers/project_relationships_controller.rb:12:in `destroy'
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",["projectuser_id"],:name => "index_project_relationships_on_projectuser_id"
的routes.rb
resources :projects do resources :comments member do get :following end end resources :project_relationships,only: [:create,:destroy]
project_relationship.rb
class ProjectRelationship < ActiveRecord::Base attr_accessible :projectuser_id belongs_to :user,foreign_key: "follower_id" belongs_to :project,foreign_key: "projectuser_id" end
project.rb
has_many :project_relationships,foreign_key: "projectuser_id" has_many :favorited_by,through: :project_relationships,source: :user
user.rb
has_many :project_relationships,foreign_key: "follower_id" has_many :followed_projects,source: :project def following_project?(project) project_relationships.find_by_projectuser_id(project.id) end def follow_project!(project) project_relationships.create!(projectuser_id: project.id) end def project_unfollow!(project) project_relationships.find_by_projectuser_id(project.id).destroy end
project_relationships_controller.rb
class ProjectRelationshipsController < ApplicationController def create @project = Project.find(params[:project_relationship][:projectuser_id]) current_user.follow_project!(@project) redirect_to @project end def destroy @project = ProjectRelationship.find(params[:id]).project current_user.unfollow_project!(@project) redirect_to @project end end
项目/ show.html.erb
<%= render 'follow_form' if signed_in? %>
项目/ _follow_form.html.erb
<% if current_user.following_project?(@project) %> <%= render 'unfollow' %> <% else %> <%= render 'follow' %> <% end %>
项目/ _follow.html.erb
<%= form_for(current_user.project_relationships.build(projectuser_id: @project.id)) do |f| %> <div><%= f.hidden_field :projectuser_id %></div> <%= f.submit "Follow",class: "btn btn-large btn-primary" %> <% end %>
项目/ _unfollow.html.erb
<%= form_for(current_user.project_relationships.find_by_projectuser_id(@project),html: { method: :delete }) do |f| %> <%= f.submit "Unfollow",class: "btn btn-large" %> <% end %>
项目/ _followerstats.html.erb
<%= @project.favorited_by.count %>