Association for polymorphic belongs_to of a particular type

前端 未结 5 925
小鲜肉
小鲜肉 2020-12-14 08:26

I\'m relatively new to Rails. I would like to add an association to a model that uses the polymorphic association, but returns only models of a particular type, e.g.:

<
5条回答
  •  暖寄归人
    2020-12-14 08:32

    I have found a hackish way of getting around this issue. I have a similar use case in a project of mine, and I found this to work. In your Note model you can add associations like this:

    class Note
      belongs_to :volunteer, 
        ->(note) {where('1 = ?', (note.subject_type == 'Volunteer')},
        :foreign_key => 'subject_id'
    end
    

    You will need to add one of these for each model that you wish to attach notes to. To make this process DRYer I would recommend creating a module like so:

     module Notable
       def self.included(other)
         Note.belongs_to(other.to_s.underscore.to_sym, 
           ->(note) {where('1 = ?', note.subject_type == other.to_s)},
           {:foreign_key => :subject_id})
       end
     end
    

    Then include this in your Volunteer and Participation models.

    [EDIT]

    A slightly better lambda would be:

     ->(note) {(note.subject_type == "Volunteer") ? where('1 = 1') : none}
    

    For some reason replacing the 'where' with 'all' does not seem to work. Also note that 'none' is only available in Rails 4.

    [MOAR EDIT]

    I'm not running rails 3.2 atm so I can't test, but I think you can achieve a similar result by using a Proc for conditions, something like:

    belongs_to :volunteer, :foreign_key => :subject_id, 
      :conditions => Proc.new {['1 = ?', (subject_type == 'Volunteer')]}
    

    Might be worth a shot

提交回复
热议问题