2

一意のカテゴリを含むカテゴリのテーブルがあります。また、投稿はこれらのカテゴリのいずれかにリンクする必要があります。次の方法でカテゴリを選択するためのチェックボックスを追加しようとしました。

  1. 値としてカテゴリの を含む「post[categoriesss][]」というフィールドに、カテゴリを含むチェックボックスを追加し:idます。
  2. newandメソッドを更新して、updateこれらの ID を取得し、関連付けられたカテゴリを収集してから、ドキュメント<<に記載されているように、演算子を介して各カテゴリをカテゴリ属性に追加します。

複数のコントローラーでこれを行う必要がないように、コードを に追加しましたnewupdate

ただし、次のエラーが発生します。

カテゴリの未定義のプロパティまたは関係 '<<'

ここで何が間違っていますか?私たちの目標を達成するための別の方法はありますか? 私たちのコードは以下です。

class Post
  include DataMapper::Resource  

  property :id,               Serial

  has n, :categories, :through => Resource

  def self.new(hash={})


    if hash.key? :categoriesss
      hash[:categoriesss].each do |category|
        categories << Category.get(category)
      end
      hash.delete! :categoriesss
    end    

    super hash
  end

end

class Category
  include DataMapper::Resource  

  property :id,       Serial
  property :name,     String,   :required => true

  has n, :rekenservices, :through => Resource
end
  <% Category.all.each do |category| %>
    <label>
      <input type="checkbox" name="post[categoriesss][]" value="<%= category.id %>" />
      <%= category.name %>
    </label>
  <% end %>

更新: チェックボックスの名前を に戻し、メソッドとメソッドを次categoriesのように更新しました。newupdate

  def self.new(hash={})
      if hash.key? :categories
        hash[:categories].map! {|id| Category.get id}
      end    
      super hash
  end

  def update(hash={})
    if hash.key? :categories
      hash[:categories].map! {|id| Category.get id}
    end    
    super hash
  end

カテゴリの追加は初めて機能します。追加のカテゴリのチェックを更新するときにもうまく機能します。ただし、カテゴリのチェックを外すと、エラー メッセージが表示されます。

列 category_id、post_id が一意ではありません

4

0 に答える 0