单表继承的一对多关系问题 (Rails)
我对 STI 和 ActiveRecord 中的关系有疑问。我想我错过了类方法中的一些内容,但我不确定。下面是我的模型:
class User < ActiveRecord::Base
has_many :advertisements
end
class Advertisement < ActiveRecord::Base
belongs_to :user
end
class FreeAdvertisement < Advertisement
end
class PaidAdvertisement < Advertisement
end
现在我想找到某个用户下的所有 FreeAdvertisement,例如:
u = User.find_by_username('myself')
@freebies = u.free_advertisements.all
它给出错误:
undefined method `free_advertisements' for #<User:0x2360f18>
我可以使用 u.advertisements.find :all, :conditions
破解它,但事实并非如此我想做。 请帮我解决这个问题。提前致谢。
I have problem with STI and relationship in ActiveRecord. I think I missed something in the class methods, but I don't know for sure. Below is my models:
class User < ActiveRecord::Base
has_many :advertisements
end
class Advertisement < ActiveRecord::Base
belongs_to :user
end
class FreeAdvertisement < Advertisement
end
class PaidAdvertisement < Advertisement
end
Now I want to find all FreeAdvertisement under certain user, e.g:
u = User.find_by_username('myself')
@freebies = u.free_advertisements.all
It gives error:
undefined method `free_advertisements' for #<User:0x2360f18>
I can hack it by using u.advertisements.find :all, :conditions
, but that's not that I want to do.
Please help me to solve this problem. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你想要的是:
I think what you want is: