Showing data from a join table ( HABTM )

I have two tables with a simple has_and_belongs_to_many relationship.

class Author < ActiveRecord::Base
has_and_belongs_to_many :sources
end

class Source < ActiveRecord::Base
has_and_belongs_to_many :authors
end

Naturally I have an Authors table, a Sources table, and an
AuthorsSources table.

I have created a form with no problem, and the form saves the authors
and sources and their relationship correctly.

Now I’m trying to set up the view for the show method, where users can
see the Source and all of the Authors associated with it.

How do I go about doing this? I’ve looked all over the place, and can’t
find any pointers. Let me know if you need any more information.

Thank you!

Morgan K. wrote:

I have two tables with a simple has_and_belongs_to_many relationship.

class Author < ActiveRecord::Base
has_and_belongs_to_many :sources
end

class Source < ActiveRecord::Base
has_and_belongs_to_many :authors
end

Naturally I have an Authors table, a Sources table, and an
AuthorsSources table.

I have created a form with no problem, and the form saves the authors
and sources and their relationship correctly.

Now I’m trying to set up the view for the show method, where users can
see the Source and all of the Authors associated with it.

How do I go about doing this? I’ve looked all over the place, and can’t
find any pointers. Let me know if you need any more information.

Thank you!

Well, I guess you’d want to start in your SourcesController#show method.

def show
@source = Source.find(params[:id])
end

Then in your view, something like this:
<% @source.authors.each do |author| %>
<%= author.full_name %>
<%end%>

You should certainly play around in script/console to get a feel for the
instance methods that come along with a habtm relationship.
See “Auto Generated Methods” found here:
http://www.ruby-forum.com/topic/162890?reply_to=715361#postform

http://www.ruby-forum.com/topic/162890?reply_to=715361#postform

Replace that link with this:

Lake

Then in your view, something like this:
<% @source.authors.each do |author| %>
<%= author.full_name %>
<%end%>

Thank you! I was trying to make it way too hard on myself by trying to
access the join table… Rails is often more automagic than I expect it
to be!