2010-07-02 1 views
1

간단한 블로그를 만드는 동안 Sinatra 및 DataMapper를 배우는 것을 봤습니다. 다 대 다 협회가 작동하는 데 문제가있는 것 같습니다. 게시물과 카테고리를 연결하려고합니다. 게시물 작성시 카테고리 연관은 작성되지 않습니다.DataMapper Sinatra를 사용하는 다 대다 연관

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 %> 

내가 뭘 잘못하고 있는거야?

감사

+0

게시 개체를 만들고 저장하는 방법을 코드로 표시 할 수 있습니까? –

답변

0

나는 datamapper 제한된 경험을 가지고,하지만 당신은 ID의 모두에 :key => true를 정의해야 할 것?

+0

직렬 속성은 기본적으로': key => true'입니다. – AlexQueue

1

@Mika Tuupola가 지적했듯이 documentation for Datamapper ("Has, and many, many-to-many)"섹션에 대한 힌트가 있습니다. 모델을 올바르게 설정 한 것처럼 보입니다. 모델을 사용할 때 문제가있을 수 있습니다.

post = Post.create 
category = Category.create 

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

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