RecipesController中的ActionController :: InvalidAuthenticityToken#在使用HABTM关联时创建

时间:2015-10-20 22:57:36

标签: ruby-on-rails

我正在开发一个Rails 4应用程序并尝试在Category和Recipe之间实现HABTM关系。我收到了上述错误。我跟着在视频中工作但没有为我工作的railscast。我添加了强大的参数。

架构:

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>

1 个答案:

答案 0 :(得分:0)

错误与CSRF (Cross-Site Request Forgery)

有关

这基本上意味着您未在布局中设置了csrf_meta_tags元标记,或者您的控制器本身存在问题。

使用带有CSRF元标记的form_for帮助程序(原样)应解决此问题。

另外,您可能希望对validates使用多声明:

#app/models/recipe.rb
class Recipe < ActiveRecord::Base
  validates :name, :source, :servings, :comment, presence: true
end

...以及表单的一些循环:

<%= form_for @recipe do |f| %>
  <% %i(name source servings comment).each do |attr| %>
     <%= f.label attr %>
     <%= f.text_field attr %>
  <% end %>   
  <%= f.collection_check_boxes :category_ids, Category.all, :id, :name %>
  <%= f.submit %>
<% end %>

您也不应该使用<p>标记进行格式化 - 使用CSS

您可以使用CSS中的margin属性来获得所需的结果:

form input {
   margin: 10px 0;
}