belongs_to with :conditions in Rails 4

♀尐吖头ヾ 提交于 2019-12-12 02:46:05

问题


I have two models, Users and Accounts:

class User < ActiveRecord::Base
  belongs_to :account, :conditions=>proc{" company_account = #{self.company_user} "}
end

class Account < ActiveRecord::Base
  has_many :users
end

In Rails 3 belongs_to and :conditions=> works fine, but in Rails 4 I read this options is not valid.

I tried belongs_to :account, -> {where company_account: self.company_user} but I get error undefined methodcompany_user

How can I solve this in Rails 4?


回答1:


Try something like:

belongs_to :account, -> { where("company_account_id = ?", self.send(:company_user).id) }



回答2:


I solved my problem, by using a composed primary key in my Account model.

For this, I used this gem



来源:https://stackoverflow.com/questions/24275835/belongs-to-with-conditions-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!