Your code should work fine given that you have a user_id
attribute on the Task
to act as the foreign key, or you can specify the foreign key in the association on User
model as follows:
class User < ActiveRecord::Base
has_many :tasks, foreign_key: "uid"
end
Now the problem is, you can't use belongs_to
on ActiveResource
so unless you need to retrieve the user
from an instance of the Task
class, you can just remove it and the other side of the relation will still work, however, if you need to retrieve the user
then you'd have to either implement your own finder method as follows:
class Task < ActiveResource::Base
schema do
string 'created_by' #email
# other fields
end
def user
@user ||= User.find self.user_id # use the attribute name that represents the foreign key
end
def user=(user)
@user = user
self.update_attribute(:user_id, user.id)
end
end
This will basically behave the same as you would expect on an ActiveRecord
model, however this can be tiresome if you have multiple associations so you can instead extend the ActiveResource
module to add belongs_to
as follows:
module BelongsToActiveResource
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def belongs_to( name, options = {} )
class_eval %(
def #{name}
@#{name} ||= name.to_s.classify.find( name.id )
end
def #{name}=(obj)
@#{name} ||= obj
self.update_attribute((name.to_s + "_id").to_sym, @#{name}.id
end
)
end
end
end
ActiveResource::Base.class_eval { include BelongsToActiveResource }
This will allow you to use belongs_to on any ActiveResource
model.
P.S.: the above solution was inspired by https://mcmap.net/q/1764704/-rails-3-1-0-belongs_to-activeresource-no-longer-working