Refactor Link Table relationsip

17 views
Skip to first unread message

Jan Yo

unread,
Jul 11, 2014, 5:27:42 PM7/11/14
to rubyonra...@googlegroups.com
I need some code refactored as it is very ugly.

memberships = customer.companies.collect(&:name).sort().join(',')

for membership in customer.memberships
membership.membership_roles.each do |membership_role|
cust_roles << membership_role.role.name + ", "
end
end

Here's the active record relation:

customer has many memberships
membership_role belongs to membership and role (link table)

Is there a more compact, cleaner way to write this?

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Jul 11, 2014, 5:39:30 PM7/11/14
to rubyonra...@googlegroups.com
Specify membership has_many roles through membership_role, then you
can use membership.roles, which helps a bit.

Colin

Jan Yo

unread,
Jul 11, 2014, 6:19:43 PM7/11/14
to rubyonra...@googlegroups.com
Colin Law wrote in post #1152183:
I was looking for better, more compact code after the for statement.

Colin Law

unread,
Jul 12, 2014, 3:06:52 AM7/12/14
to rubyonra...@googlegroups.com
With has_many through then you can use collect and join on membership.roles

Colin
Reply all
Reply to author
Forward
0 new messages