Rails - Multiple Index Key Association

前端 未结 2 1528
悲哀的现实
悲哀的现实 2021-01-01 05:33

There seem to be a number of ways to handle a multiple foreign key association. Each way I have approached this has their draw backs, and as I am new to Rails I am convinced

相关标签:
2条回答
  • 2021-01-01 05:52

    I did find the solution to this, however it turned out I was probably asking the wrong question. I have not found away to have multiple index keys as I asked without implementing some custom sql which breaks different rails helpers.

    I guess my question still stands, but how I did resolve this was to look at the problem differently. I just created the associations as they are:

    belongs_to :rcvd_person, :class_name => 'Person', :foreign_key => :rcvd_id
    belongs_to :origin_person, :class_name => 'Person', :foreign_key => :origin_id
    

    And a custom sql statement:

    class Person...
      has_many :links, :finder_sql => 'SELECT * FROM links WHERE origin_id = #{id} OR rcvd_id = #{id}'
    end
    

    Then I was able to manipulate the records how I wanted in my view. In case anyone else is doing something similar, I did:

    <% person.links.each do |link| %> 
    
      <% if link.origin_id == person.id %>
        <%= link.rcvd_person.given_name %>
      <% else %>
        <%= link.origin_person.given_name %>
      <% end  %>
    
    <% end %>
    
    0 讨论(0)
  • 2021-01-01 06:02

    I'm not sure you can really support an association with multiple keys in the same table because Rails won't know which key to set if you attempt to create a relationship.

    However, if you just want person.links, Rails 3 provides a way that is better than :finder_sql

    class Link
      def self.by_person(person)
        where("origin_id => :person_id OR rcvd_id => :person_id", :person_id => person.id
      end 
    end
    
    class Person < ActiveRecord::Base
      # You can include the has_many relationships if you want, or not
    
      def links
        Link.by_person(self)
      end 
    end
    

    This lets you do things like @person.links.limit(3) (which currently appears to be broken when using :finder_sql)

    0 讨论(0)
提交回复
热议问题