【发布时间】:2010-07-02 05:01:20
【问题描述】:
我只是在构建一个简单的博客时开始学习 Sinatra 和 DataMapper。我似乎遇到了让我的多对多关联工作的问题。我正在尝试将类别与帖子相关联。创建帖子后,不会创建类别关联。
这是我的模型:
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 成功构建 category_posts 表。我认为我的创建表单中的代码不正确。
<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>
我尝试在 category_posts 表中手动创建条目,但没有显示任何记录。这是我的观点中与类别相关的部分。该计数用于调试,它始终为 0。
<%= @post.categories.count %>
<% @post.categories.each do |category| %>
<p>Test: <%= category.title %></p>
<% end %>
任何想法我做错了什么?
谢谢
【问题讨论】:
-
你能告诉我们你如何创建和保存 Post 对象的代码吗?
标签: ruby sinatra datamapper