【问题标题】:DataMapper Many-To-Many Association using Sinatra使用 Sinatra 的 DataMapper 多对多关联
【发布时间】: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


【解决方案1】:

documentation for Datamapper(“拥有并属于许多(或多对多)”部分)有一些提示,正如@Mika Tuupola 指出的那样,看起来您已正确设置模型,问题可能在于使用您的模型:

post  = Post.create
category = Category.create

# link them by adding to the relationship
post.categories << category
post.save

p post.categories # => [#<Category @id=1>]

【讨论】:

    【解决方案2】:

    我对 datamapper 的经验有限,但您需要在两个 ID 上都定义 :key =&gt; true 吗?

    【讨论】:

    • 串行属性默认为:key =&gt; true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多