Topic: Need Relationship Help

I've been having a bit of a problem.  I have a post model that the users can make posts in.  I also have a resource model that users can also upload files through.  Now, if the users specify a certain date in the post, that post should attach the file if the file also has that certain date marked.  Now, my problem is getting the relationship to work.  I had a has_and_belongs_to_many on both of them, but that didn't seem to work.  Since I have gotten rid of both of them, it seems to work OK but I totally don't understand why.

Also, I think there is some really crummy coding in this.  Let me show you.

class MainController < ApplicationController
 
  def index
    @post = Post.find(:all, :order => "postdate DESC")
    @resource
  end

module MainHelper
 
  def find_resource(electiondate)
    @resource = Resource.find(:all, :conditions => ["election_date = ?", electiondate] )
  end

end


And then finally my view:

<div id="blog">
    <% for post in @post %>
            <h2><%= post.title %></h2><h3><%= post.postdate %></h3>
            <span class="blogtext"><%= post.body %></span>
            <ul>
            <% find_resource(post.electiondate) %>
            <% if @resource.nil? %>
            <% else %>
                <% for resource in @resource %>
                    <li><%= resource.title %> - <a href=></li>
                <% end %>
            <% end %>
           
            </ul>
    <% end %>
</div>

Anyone have a better way to make this work, or is this actually the best way?

Kyle Daigle
Newb' Ruby on Rails Programmer

Re: Need Relationship Help

You can improve your current code by moving the resource find logic into the Post model:

# in Post model
def resources
  Resource.find_all_by_election_date(electiondate)
end

# controller
  def index
    @posts = Post.find(:all, :order => "postdate DESC")
  end

# view
<div id="blog">
  <% for post in @posts %>
      <h2><%= post.title %></h2><h3><%= post.postdate %></h3>
      <span class="blogtext"><%= post.body %></span>
      <ul>
        <% for resource in post.resources %>
          <li><%= resource.title %> - <a href=></li>
        <% end %>
      </ul>
  <% end %>
</div>


Associations are set primarily by relating "id" integer columns, not date columns. If you want something related by date alone it is best to just make a method in the model to fetch the related models as I have done.

That said, if you want to relate the models using "id" columns then that is entirely possible, but how exactly depends on the interface of your application.

Railscasts - Free Ruby on Rails Screencasts