私は Rails プログラミングを始めていますが、達成したいのは、製品に対応するカテゴリを選択できるチェック ボックスのリストを用意することだけです。この件についてレールキャストをフォローしましたが、うまくいかないようです。
Rails 3.0.9 と Ruby 1.8.7 を使用しています。
モデルを適切にセットアップし、結合テーブルの移行も行いました。商品を編集しようとすると、category_ids が POST されますが、データベースには保存されません。
ログ:
Started POST "/products/1" for 127.0.0.1 at Mon Sep 19 01:39:33 +0300 2011
Processing by ProductsController#update as HTML
Parameters: {"commit"=>"Update Product", "authenticity_token"=>"x2Z5GGiNh9yLz6xjuQaMqdGW3Gw7dYe8dSghyrFpiYk=", "utf8"=>"���", "id"=>"1", "product"=>{"name"=>"Magicianulx2", "price"=>"121", "category_ids"=>["1"]}}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = 1 LIMIT 1
WARNING: Can't mass-assign protected attributes: category_ids
Redirected to http://localhost:3000/products/1
Completed 302 Found in 10ms
Started GET "/products/1" for 127.0.0.1 at Mon Sep 19 01:39:33 +0300 2011
Processing by ProductsController#show as HTML
Parameters: {"id"=>"1"}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = 1 LIMIT 1
Rendered products/show.html.erb within layouts/application (4.2ms)
Completed 200 OK in 11ms (Views: 6.1ms | ActiveRecord: 0.2ms)
モデル:
class Product < ActiveRecord::Base
attr_accessible :name, :price
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :products
end
移行 :
class AddCategoriesProducts < ActiveRecord::Migration
def self.up
create_table :categories_products, :id => false do |t|
t.integer :category_id
t.integer :product_id
end
end
def self.down
drop_table :categories_products
end
end
コントローラー(製品コントローラーでの更新方法)
def update
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
redirect_to @product, :notice => "Successfully updated product."
else
render :action => 'edit'
end
end
ビュー/製品の私の _form.html.erb
<%= form_for @product do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>
<% for category in Category.find(:all) %>
<div>
<%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>
<%= category.name %>
</div>
<% end %>
<p><%= f.submit %></p>
<% end %>
コントローラーとビューはすべて、気の利いた足場を使用して生成されました。他のすべては問題なく動作しているように見えますが、チェック ボックスの値はデータベースに保存されません。Railsコンソールを介して手動で追加すると、問題なく機能します。私が間違っていることについてのアイデアはありますか?