我正在研究Rails 4應用程序並試圖實現類別和配方之間的HABTM關係。我收到上述錯誤。我跟着一個在視頻中工作過的railscast,但沒有爲我工作。我添加了強大的參數。ActionController :: RecipesController中的InvalidAuthenticityToken#使用HABTM協會時創建
模式:
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "categories_recipes", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "recipe_id"
end
create_table "recipes", force: :cascade do |t|
t.string "name"
t.string "source"
t.string "servings"
t.string "comment"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Models:
class Category < ActiveRecord::Base
has_and_belongs_to_many :recipes
validates :name, :presence => true
end
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :categories
validates :name, :presence => true
validates :source, :presence => true
validates :servings, :presence => true
validates :comment, :presence => true
end
形式:
<%= form_for @recipe do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :source %>
<%= f.text_field :source %>
</p>
<p>
<%= f.label :servings %>
<%= f.text_field :servings %>
</p>
<p>
<%= f.label :comment %>
<%= f.text_field :comment %>
</p>
<%= hidden_field_tag 'recipe[category_ids]', nil %>
<% Category.all.each do |category| %>
<p>
<%= check_box_tag 'recipe[category_ids][]', category.id, @recipe.category_ids.include?(category.id) %>
<%= category.name %>
</p>
<% end %>
<%= f.submit %>
<% end %>
recipes_controller.rb:
def create
@recipe = Recipe.new(recipe_params)
if @recipe.save
redirect_to recipes_path
else
render :new
end
end
private
def recipe_params
params.require(:recipe).permit(:name, :source, :servings, :comment, {category_ids:[]})
end
layout.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Friends</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
你檢查出這個問題? http://stackoverflow.com/questions/3364492/actioncontrollerinvalidauthenticitytoken – wspurgin
嘗試從強大的參數中去除'category_ids:[]'周圍的{大括號}。 –
我試過了,但沒有改變任何東西。不管怎麼說,還是要謝謝你。 – jkfairless