views:

45

answers:

1

I just stared learning Sinatra and DataMapper while building a simple blog. I seem to have encountered a problem getting my Many-To-Many association working. I'm trying to associate categories with posts. Upon creation of a post, the category association is not created.

Here are my models:

class Post

  include DataMapper::Resource

  has n, :categories, :through => Resource

  property :id,             Serial
  property :title,          String
  property :slug,           String
  property :body,           Text
  property :description,    Text
  property :created_at,     DateTime
  property :updated_at,     DateTime
  property :posted_at,      DateTime

end

class Category

  include DataMapper::Resource

  has n, :posts, :through => Resource

  property :id,             Serial
  property :title,          String

end

DataMapper successfully builds the category_posts table. I don't think the code is correct in my create form.

 <form action="/post/create/" method="post">
        <% @category = Category.all %> 
        <% @category.each_with_index do |cat,i| %>
            <input id="category<%=i%>" type="checkbox" value="<%= cat.title %>" name="post.category.<%=cat.id%>" />
            <label for="category<%=i%>"><%= cat.title%></label>
        <% end %>
    <p>
            <input type="submit">
        </p>
    </form>

I have tried manually creating entries in the category_posts table and no records show up. Here is the part of my view related to categories. The count is for debugging, it always reads 0.

<%= @post.categories.count %>
    <% @post.categories.each do |category| %>
        <p>Test: <%= category.title %></p>
    <% end %>

Any ideas what I am doing wrong?

Thanks

A: 

I've got limited experience with datamapper, but do you need to define :key => true on both of the IDs?

Tom