Accessing associated table data with rails.

To access data that has related data using has_many and belongs_to, first make sure you?ve set up your related ids. For example for the two models posts and attachments, the attachments table should have a field called post_id so that the attachment can be association to the post.

Then make sure you have the appropriate has_many and belongs_to in the models

Then do the following in your view code:

                <% @posts.attachments.each do |post| %>
    <img src="<%= attachment.public_filename %>" class="attachment" /><br />
<% end%>

Comments