I just stared learning Sinatra and DataMapper while building a sim开发者_Python百科ple 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
The documentation for Datamapper (section for "Has, and belongs to, many (Or Many-To-Many)") has some hints, as @Mika Tuupola points out, it looks like you've set up your models correctly, the problem might be in using your models:
post = Post.create
category = Category.create
# link them by adding to the relationship
post.categories << category
post.save
p post.categories # => [#<Category @id=1>]
I've got limited experience with datamapper, but do you need to define :key => true
on both of the IDs?
精彩评论