【发布时间】:2015-12-26 04:50:27
【问题描述】:
您好,我正在尝试构建一个类似 twitter 的示例应用程序。我创建了一个关系模型,在我看来,我有两种形式,一种带有关注按钮,另一种带有取消关注按钮,看起来像这样。
<% if current_user.following?(@otheruser) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
我在 _follow.html.erb 中喜欢
<%= form_for(current_user.active_relationships.build) do |f| %>
<div><%= hidden_field_tag :followed_id, @otheruser.id %></div>
<%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>
在 _unfollow.html.erb 之类的
<%= form_for(current_user.active_relationships.find_by(followed_id: @otheruser.id),
html: { method: :delete }) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-danger" %>
<% end %>
在我的 user.rb 中 我有像
这样的方法和关联has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end
# 取消关注用户。
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end
每当我点击关注按钮时,它都会在relationship.rb中的关系模型中创建一个条目
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
但是当我点击取消关注按钮时,它给出的错误是“找不到与'id'的关系=” 任何人都可以帮助我了解如何显示 user.followers 和 user.following 的东西。
在关系控制器中就像
class RelationshipsController < ApplicationController
def index
@otheruser = User.find_by_username(params[:name])
@reviews = @otheruser.write_reviews.all
@followers = @otheruser.followers
end
def create
user = User.find(params[:followed_id])
current_user.follow(user)
redirect_to followuser_url
end
def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
redirect_to followuser_url
end
end
关系表看起来像
create_table "relationships", force: :cascade do |t|
t.integer "follower_id", limit: 4
t.integer "followed_id", limit: 4
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
【问题讨论】:
-
让我们看看你的控制器
-
我已经更新了我的问题,请参考。
-
点击取消关注btn时调用哪个方法
-
关系#destroy
-
请任何人帮忙...
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord