Forum: Ruby on Rails MTM relationship with relationship attributes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Aebb836b5b2f9a6476d0107d12c84991?d=identicon&s=25 vishu.raj (Guest)
on 2007-03-05 18:00
(Received via mailing list)
I have following many to many relationship:
class Service < ActiveRecord::Base
has_many :service_dependencies
has_many :dependents, :through => :service_dependencies
end

class ServiceDependency < ActiveRecord::Base
belongs_to :service
belongs_to :dependent, :class_name => 'Service', :foreign_key =>
'dependent_service_id'
end

However, in my schema the MTM table service_dependencies has few
relationship attributes as well, e.g. impact, severity, etc. along
with the foreign keys.

Right now, I'm displaying the dependent services' fields in following
manner:
<%=h dependents.send("service_name") %>

<% for dependents in @service.dependents %>
     <b>Service Name:</b><br> <%=h dependents.send("service_name")
%><br>
<% end %>

I also want to display the relationship attributes, could someone
please help me by letting me know how to access them in my view page?
Aebb836b5b2f9a6476d0107d12c84991?d=identicon&s=25 Vishwaraj (Guest)
on 2007-03-06 13:32
Hi,

I found out the solution myself by refering to several examples and
forums. It is as easy as this:

<% for dependent in @service.dependents %>
      <b>Service Name:</b><br> <%=h dependent.send("service_name")
%><br>
      <% dependency = @service.service_dependencies.find(:first,
:conditions =>
            ["dependent_service_id = ?", dependent.id])%>
      <b>Impact:</b><br> <%=h dependency.send("impact") %><br>

<%end%>

This may be helpful for some other beginner like me.

Thanks and Regards,
Vishu
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2007-03-06 14:16
(Received via mailing list)
Vishwaraj wrote:
>             ["dependent_service_id = ?", dependent.id])%>
>       <b>Impact:</b><br> <%=h dependency.send("impact") %><br>
>
> <%end%>
>
> This may be helpful for some other beginner like me.

Better would be

<% sds = @service.service_dependents.find(:all, :include => :dependent)
    for service_dependent in sds %>
<b>Service Name:</b><br>
<%= h service_dependent.dependent.service_name %><br>
<b>Impact:</b><br>
<%= h service_dependent.impact %><br>
<%end%>


--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.