Rails - Multiple Index Key Association

前端 未结 2 1575
悲哀的现实
悲哀的现实 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 %>
    

提交回复
热议问题