(对不起我的英文)
如果我想上传包含:name
和:date
参数的新记录,那就是我发现的内容:
控制器:
class ActorController < ApplicationController
def index
end
def new
@actor = Actors.create
end
def create
@actor = Actors.create(params[:actors])
if @actor.save
redirect_to actor_path, :notice => "Your actor was saved."
else
render "new"
end
end
end
型号:(actors.rb)
class Actors < ActiveRecord::Base
attr_accessible :birth, :name
end
和视图:(new.html.erb)
<%= form_for(@actor) do |a| %>
<%= a.text_field :name %>
<%= a.text_field :birth %>
<%= a.submit %>
<% end %>
我在本地服务器控制台中的输出是:
Started PUT "/actor/40" for 127.0.0.1 at 2013-03-27 13:38:15 +0100
Processing by ActorController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BKhrP1Rfkco7r05wPT758M3CHQXRP5l5jcul77oTLPw=", "actors"=>{"name"=>"Bunny", "birth"=>"19/21/21"}, "commit"=>"Update Actors", "id"=>"40"}
(1.2ms) begin transaction
SQL (0.7ms) INSERT INTO "actors" ("birth", "created_at", "name", "updated_at") VALUES (?, ?, ?, ?) [["birth", nil], ["created_at", Wed, 27 Mar 2013 12:38:15 UTC +00:00], ["name", nil], ["updated_at", Wed, 27 Mar 2013 12:38:15 UTC +00:00]]
(197.8ms) commit transaction
(0.2ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/actor/40
Completed 302 Found in 209ms (ActiveRecord: 200.0ms)
答案 0 :(得分:3)
请编辑以下内容:
1)编辑您的模型:
class Actor < ActiveRecord::Base # Class name should be Singular
attr_accessible :birth, :name
end
2)编辑您的控制器:
class ActorsController < ApplicationController # Note Here the controller name should be plural without space
def index
end
def new
@actor = Actor.new # In the new action, it should be classname.new not create
end
def create
@actor = Actor.create(params[:actor]) # Here also the Actor class name should be singular
if @actor.save
redirect_to actor_path, :notice => "Your actor was saved."
else
render "new"
end
end
end
PS:
1)在View文件夹中,名称也应为Plural,因此您的文件夹名称为app/view/actors
。
2)更改您的控制器名称,如actors_controller
。
3)在您的路线中,它应为resources :actors
。
4)您需要通过正确的修改来对齐代码,以找到您的起点和结束位置。这是开始编码的好方法。它将解决您的50%问题,以找到您做错的地方。
答案 1 :(得分:0)
在您的控制器操作中,您的参数名称错误:
Actors.create(params[:movie]) should be Actors.create(params[:actors])
答案 2 :(得分:0)
将您的新操作代码更改为:
@actor = Actors.new
并确认您的模型类是Actors 它可能有用。
答案 3 :(得分:0)
这里有很多错误:
控制器名称应为复数,您必须将文件重命名为actors_controller.rb
模型名称应该是单数,也可以看到您将文件名更改为actor.rb
新操作应为@actor = Actors.new
而不是create
,#create是#new和#save的缩短版本。
params哈希值应为params[:actor]
class ActorsController < ApplicationController def index end def new @actor = Actor.new end def create @actor = Actor.create(params[:actor]) if @actor.save redirect_to actor_path, :notice => "Your actor was saved." else render "new" end end end
同时更改Actor.rb中的模型名称,并确保它是模型的名称。 同样在这种情况下,您应该检查您的迁移。
class Actor < ActiveRecord::Base
attr_accessible :birth, :name
end
答案 4 :(得分:0)
@actor = Actors.create
是错误的,因为它将@actor变量分配给新创建的Actors对象。这就是你在输出中看到Processing by ActorController#update as HTML
的原因,因为该对象已经创建并且正在尝试更新它。
您应该将其更改为@actor = Actors.new