我有属于类别的子类别。我的应用程序在子类别下保存(构建)我的所有子类别,id = 1,即使我的代码似乎没问题,也不应该这样做:
子类别控制器:
def create
@category = Category.find_by(params[:id])
@subcategory = @category.subcategories.build(subcategory_params)
if @subcategory.save
flash[:success] = "added subcategory"
redirect_to admin_categories_url
else
render :new
end
end
...
private
def subcategory_params
params.require(:subcategory).permit(:name, :category_id)
end
Subcategory.rb
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
validates :name, presence: true
validates :category_id, presence: true
end
形式:
<h3>Add a subcategory</h3>
<%= form_for [@category, @subcategory] do |f| %>
<%= f.text_field :name, placeholder: "Name" %>
<%= f.submit "Add a subcategory" %>
<% end %>
路由器:
resources :categories do
resources :subcategories
end
URL:
在id = 3
的类别中添加新的子类别http://localhost:3000/categories/3/subcategories/new
日志:
Started POST "/categories/1/subcategories" for 127.0.0.1 at 2014-04-16 16:04:47 +0400
Processing by SubcategoriesController#create as HTML
Parameters: {"utf8"=>"✓", authenticity_token"=>"74U3VyAN6NqEjhkuHGNHnPda/yzpc+dIcn2xBJ6Zi2A=", "subcategory"=>{"name"=>"A name"}, "commit"=>"Add subcategory", "category_id"=>"1"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT 1 [["id", 1]]
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO "subcategories" ("category_id", "created_at", "name", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["category_id", 1], ["created_at", "2014-04-16 12:04:47.151729"], ["name", "A name"], ["updated_at", "2014-04-16 12:04:47.151729"]]
(0.8ms) COMMIT
我是1
这里有什么问题?
更新
做的时候
@category = Category.find_by(params[:category_id])
出现此错误:
ERROR: argument of WHERE must be type boolean, not type integer
LINE 1: SELECT "categories".* FROM "categories" WHERE (1) LIMIT 1
如果正在做
@category = Category.find(params[:category_id])
问题主义者
答案 0 :(得分:5)
在您的create
操作中,您将获取子类别的ID,而不是类别。将其更改为:
def create
@category = Category.find(params[:category_id])
...
同样需要在@category
方法中设置new
,以便category_id
在视图中的参数中返回3。当然,这个复制也可以使用控制器中的辅助方法进行干扰。
要查看ID的差异,您可以使用rake routes
,您应该看到类似的内容:
new_category_subcategory GET /categories/:category_id/subcategories/new subcategories#new
这表明它需要参数category_id
作为类别的id。
答案 1 :(得分:1)
查看您的参数category_id
而不是id
Parameters: {"utf8"=>"✓", authenticity_token"=>"74U3VyAN6NqEjhkuHGNHnPda/yzpc+dIcn2xBJ6Zi2A=", "subcategory"=>{"name"=>"A name"}, "commit"=>"Add subcategory", "category_id"=>"1"}
#=&GT; &#34; CATEGORY_ID&#34; = GT;&#34; 1&#34;
Category.find_by(category_id: params[:category_id])
所以你需要做
def create
@category = Category.find_by(category_id: params[:category_id])
@subcategory = @category.subcategories.build(subcategory_params)
if @subcategory.save
flash[:success] = "added subcategory"
redirect_to admin_categories_url
else
render :new
end
end