Rails using a join model attribute in a condition for a find

末鹿安然 提交于 2020-01-06 06:45:36

问题


I'm using a :has_many, :through association to link two models, User and Place

It looks like this -

In User:

  has_many :user_places
  has_many :places, :through=>:user_places

In Place:

  has_many :user_places
  has_many :users, :through=>:user_places

In User_Place

  belongs_to :user
  belongs_to :place
  belongs_to :place_status

On that last one note the place_status.

I want to write a find that returns all places associated to a user with a particular place_status_id.

Place_Status_id is on the join model, user_place.

So basically I want

User.places.where(:place_status_id=>1)

(in rails 3)

but i get an error with that because place_status_id isnt on the place model.

Any ideas? Thanks all.


回答1:


I believe you can do your find this way

@user.places.joins(:user_places).where(:user_places => {:place_status_id => 1})

I've never used Rails 3, so I'm sorry if there's any errors.



来源:https://stackoverflow.com/questions/3250947/rails-using-a-join-model-attribute-in-a-condition-for-a-find

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