I have set up a twitter-like following model. Users can all subscribe to each other. I am getting an error in my users controller when trying to create the relationship.
user.rb:
has_many :subscriptions
has_many :providers, :through => :subscriptions
has_many :followings, :class_name => "Subscription"
has_many :followers, :through => :followings
subscription.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
This is the error when I call follow:
ActiveRecord::UnknownAttributeError (unknown attribute: user_id):
app/controllers/users_controller.rb:73:in `follow'
I have verified that I ran rake db:migrate – the subscription table has two fields provider_id and follower_id. Can anyone help me with the error and explain why it is looking for a ‘user_id’ attribute?
Update:
show.html.erb:
<%= button_to "Subscribe", user_follow_path(@user), :remote => true %>
routes.rb:
resources :users do
resources :locations
resources :saved_events
resources :saved_locations
post "follow"
end
rake routes | grep follow:
user_follow POST /users/:user_id/follow(.:format) {:action=>"follow", :controller=>"users"}
Using Michael Hartl’s tutorial as a guide, I came up with this solution, which fixes the data model so that collection functions work as they should.
Make the provider id accessible and remove the foreign keys in the subscription model.
subscription.rb:
Add foreign keys for subscriptions and reverse_subscriptions in the user model.
user.rb:
I also added helper methods to the user model.
user.rb:
Then, in the controller, we can call follow! or unfollow!
user_controller.rb: