Porting complicated has_many relationships to Rails >4.1 (without finder_sql)

前端 未结 2 1569
眼角桃花
眼角桃花 2021-01-05 22:53

I am porting a Rails app to Rails 4.2. This Rails app contains some rather complex manual SQL code in associations - partly due to DB optimizations (e.g. subselects instead

2条回答
  •  北海茫月
    2021-01-05 23:15

    Update

    I learnt a while ago that this makes no sense. A has_many relationship must have injective connections at least in one direction, so an "OR" in a SQL clause makes no sense. How should a CREATE operation decide which condition to satisfy to create a new record? This relationship is read only by definition and so it is not a has_many relationship.

    In this case, a simple class method (or scope) would be the right answer instead of has_many. To concatenate results from several queries use something like

    def internal_messages
      InternalMessage.where( id: sent_message_ids + received_message_ids)
    end
    

    to keep the resulting object chainable (i.e. @user.internal_messages.by_date etc.)

提交回复
热议问题