0

我已经建立了一个类似推特的追随者模型。用户都可以互相订阅。尝试创建关系时,我的用户控制器中出现错误。

用户.rb:

has_many :subscriptions
has_many :providers, :through => :subscriptions

has_many :followings, :class_name => "Subscription"
has_many :followers, :through => :followings

订阅.rb

belongs_to :provider, :class_name => 'User', :foreign_key => "provider_id"
belongs_to :follower, :class_name => 'User', :foreign_key => "follower_id"

users_controller.rb

69 def follow
70   logger.debug params.to_yaml
71   @user = User.find(params["user_id"])
72   logger.debug @user.to_yaml
73   if current_user.providers << @user
74     flash[:notice] = "Subscribed"
75   else
76     flash[:error] = "Unable to subscribe."
77   end
78 end

这是我调用跟随时的错误:

ActiveRecord::UnknownAttributeError (unknown attribute: user_id):
  app/controllers/users_controller.rb:73:in `follow'

我已经验证我运行了 rake db:migrate - 订阅表有两个字段 provider_id 和 follower_id。谁能帮我解决这个错误并解释它为什么要寻找“user_id”属性?

更新:

显示.html.erb:

<%= button_to "Subscribe", user_follow_path(@user), :remote => true %>

路线.rb:

resources :users do
  resources :locations
  resources :saved_events
  resources :saved_locations
  post "follow"
end

耙路线 | grep 跟随:

user_follow POST     /users/:user_id/follow(.:format)                    {:action=>"follow", :controller=>"users"}
4

2 回答 2

1

Michael Hartl 的教程为指导,我提出了这个解决方案,它修复了数据模型,以便集合函数可以正常工作。

使提供者 ID 可访问并删除订阅模型中的外键。

订阅.rb:

attr_accessible :provider_id
belongs_to :provider, :class_name => 'User'
belongs_to :follower, :class_name => 'User'

在用户模型中为订阅和 reverse_subscriptions 添加外键。

用户.rb:

has_many :subscriptions, :foreign_key => "subscriber_id", :dependent => :destroy
has_many :subscribed_to, :through => :subscriptions, :source => :provider

has_many :reverse_subscriptions, :class_name => "Subscription", :foreign_key => "provider_id", :dependent => :destroy
has_many :followers, :through => :reverse_subscriptions

我还在用户模型中添加了辅助方法。

用户.rb:

def following?(provider)
  subscriptions.find_by_provider_id(provider)
end

def follow!(provider)
  subscriptions.create!(:provider_id => provider.id)
end

def unfollow!(provider)
  subscriptions.find_by_provider_id(provider).destroy
end

然后,在控制器中,我们可以调用 follow!或取消关注!

用户控制器.rb:

...
current_user.unfollow!(@user)
...
current_user.follow!(@user)
...
于 2012-01-07T17:59:21.467 回答
0

它给你一个错误的原因是当你调用<<提供者集合时,用户不知道它应该是一个追随者。所以它基本上是在说,“我是一个用户,将我添加到这个提供者集合中!” 而不是“这家伙要跟着我,我现在是提供者,他是追随者”

最简单的答案可能是做

用户.rb:

def follow(other_user)
  Subscription.create(:provider => other_user, :follower => self)
end

users_controller.rb

def follow
  @user = User.find(params["user_id"])
  if current_user.follow(@user)
    flash[:notice] = "Subscribed"
  else
    flash[:error] = "Unable to subscribe."
  end
end
于 2012-01-05T20:34:41.440 回答