Ruby on Rails创建方法而不保存参数

时间:2013-11-16 21:41:55

标签: ruby-on-rails ruby

我的创建方法无法正常工作。提前谢谢!

<%= form_for :category, url: categories_path do |f| %>
    <p>
      <%= f.label :title %><br>
      <%= f.text_field :title %>
    </p>

    <p>
      <%= f.submit %>
    </p>
<% end %>

我的控制员:

class CategoriesController < ApplicationController
  def show
    @category = Category.where(id: params[:id]).first
  end

  def create
    @category = Category.create(title: params[:category][:title])
    redirect_to @category
  end
end 

注意:params [:category] ​​[:title]实际上是正确的值

我的模特:

class Category < ActiveRecord::Base
  has_many :events

  attr_accessor :title
end

我的迁移:

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :title

      t.timestamps
    end
  end
end

当我转到我的表单并在文本框中输入“main”(或其他任何内容)然后单击“保存”时,它将保存在我的数据库中:

 id | title |      created_a      |     updated_at      |
---------------------------------------------------------
 1  | NULL  | 2013-11-16 21:30:59 | 2013-11-16 21:30:59 |

如您所见,我无法将参数保存在数据库中。我以前没有发生过这种情况,我去尝试对我的结构进行一些更改,这个问题开始发生,所以我还原了,现在它甚至没有工作,即使我还原了。顺便说一下我使用的是mysql数据库。提前谢谢!

4 个答案:

答案 0 :(得分:5)

虽然Rails 4 支持强参数,但它需要开发人员操作才能启用它们。首先,开发人员必须在模型中包含一个模块才能打开它们:

include ActiveModel::ForbiddenAttributesProtection

如果不包括使用require / permit对,这里提到的很多都没有负面影响。 (反之亦然 - 如果你包含模块但是没有使用require / permit来清理params那么你会得到一个错误。)

Mateo的问题是很多更简单。在Category类定义中,您已包含

attr_accessor :title

这是Ruby的好形式......但不适用于Rails。 attr_accessor宏为类上名为“title”的属性创建一个getter / setter对。不幸的是,这意味着来自ActiveRecord的继承代码将创建将title属性传递到数据库或从数据库传递的魔术方法。删除标题的attr_accessor,你就可以开展业务了。

class Category
  has_many :events
end

答案 1 :(得分:1)

正如@CDub在他的回答中所说,在Rails 4中,你必须使用强参数,所以一个例子就是

class CategoriesController < ApplicationController
  def show
    @category = Category.where(id: params[:id]).first
  end

  def create
    @category = Category.create(params.require(:category).permit(:title))
    redirect_to @category
  end
end

在您的模型中,您可以删除attr_accessible

class Category < ActiveRecord::Base
  has_many :events
end

答案 2 :(得分:1)

最好使用单独的方法来允许参数。

private
  def category_params
    params.require(:category).permit(:title)
  end

然后在create方法中:

@category = Category.create(category_params)

答案 3 :(得分:0)

如果您升级到Rails 4,Rails 4现在支持使用强参数代替attr_accessibleattr_protected。由于Rails 4默认使用强参数,您的参数很可能被列入黑名单。

查看this gem,详细了解从Rails 3升级到Rails 4,以及the documentation了解Rails 3和Rails 4之间的差异。