一切似乎都不太难但我已经花了好几个小时但仍然无法让它发挥作用。
如果我在rails控制台中执行Category.create(:name =>“foo”),则会创建一个名称很新的类别。
(0.2ms) begin transaction
SQL (0.3ms) INSERT INTO "categories" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-09-16 15:40:01.218700"], ["name", "foo"], ["updated_at", "2014-09-16 15:40:01.218700"]]
(14.5ms) commit transaction
=> #<Category id: 38, created_at: "2014-09-16 15:40:01", updated_at: "2014-09-16 15:40:01", name: "foo">
但是,如果我在页面上这样做会出错。我的类别模型只有一个属性是“名称”,我希望所有这些属性都列在我的类别索引页面上。
<% @categories.each do |category| %>
<ul>
<li>
<b><%= category.name %></b><br />
<% category.products.each do |product| %>
<%= product.title %><br />
<% end %>
</li>
</ul>
<% end %>
<%= link_to "Create new category", categories_new_path %>
如果我在控制台中创建了一个带有名称的新类别,它会显示在页面上,其名称没有问题。但是如果我在页面上创建它,则会创建一个名称属性为“nil”的类别。所以请帮我弄清问题所在。我对rails非常陌生。
这是我的categories_controller.erb
class CategoriesController < ApplicationController
# load_and_authorize_resource
def new
@category = Category.new
end
def create
@category = Category.new(params[:name])
if @category.save
redirect_to categories_path
else
render 'new'
end
end
def index
@categories = Category.all
end
end
这是我的new.html.erb
<h1>New Category</h1>
<%= form_for(@category) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Back', categories_path %>
这是我点击提交按钮后服务器中显示的内容。
Started POST "/categories?locale=en" for 127.0.0.1 at 2014-09-17 00:02:42 +0800
Processing by CategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZdXcC/uEMA/jhGoGhYvp4lSHHfi/tmlm3CovJcYizJ0=", "category"=>{"name"=>"fwefewfw"}, "commit"=>"Create Category", "locale"=>"en"}
(0.1ms) begin transaction
SQL (0.2ms) INSERT INTO "categories" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-09-16 16:02:42.806041"], ["updated_at", "2014-09-16 16:02:42.806041"]]
(21.2ms) commit transaction
请注意,sql语句中没有插入“名称”。 我觉得我错过了一些非常基本的东西。原谅我是个新手,谢谢你的帮助!!
答案 0 :(得分:1)
查看您的标签,我认为您正在使用rails 4,因此您需要首先允许您的属性。你可以这样做:
class CategoriesController < ApplicationController
# load_and_authorize_resource
def create
@category = Category.new(category_params)
if @category.save
redirect_to categories_path
else
render 'new'
end
end
private
def category_params
params.require(:category).permit(:name)
end
end
答案 1 :(得分:1)
应该是:
@category = Category.new(params[:category])
如果您使用的是Rails 4,则应使用强参数并将以下方法添加到控制器中:
def category_params
params.require(:category).permit(:name)
end
然后将Category.new行更改为:
@category = Category.new(category_params)
这是新的&#34;安全&#34;在Rails模型中接受用户生成的数据的方法,并且一旦你习惯它就能很好地工作。