Form_for工作但不保存到表

时间:2015-06-16 15:09:47

标签: ruby-on-rails

我想制作一个简单的form_for,但这并不能完全发挥作用。

我有两张桌子: 用户 - > has_many - > CVS

这是我的表格:

<%= form_for(:cvs, action: "create", html: { method: :post }) do |f| %>
    Nom : <%= f.text_field :nom %><br />
    <%= f.submit %>

<% end %>

在我的控制器中:

def create
    @cv = Cv.new(cv_params)
    @cv.save
end

使用cv_params:

def cv_params
    params.require(:cv).permit(:nom)
end

在我的route.rb中:

post 'createcv'       => 'static_pages#createcv'

我的控制器是static_pages,我的视图是createcv 当我加载视图时,该字段出现,我放了一些东西,但表中没有创建(没有错误)。我该如何纠正?

编辑:

日志

Started GET "/createcv" for ::1 at 2015-06-16 17:22:03 +0200
Processing by StaticPagesController#createcv as HTML
User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Cv Load (0.0ms)  SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ?  [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (10.0ms)
Rendered layouts/_shim.html.erb (1.0ms)
Rendered layouts/_header.html.erb (2.0ms)
Rendered layouts/_footer.html.erb (1.0ms)
Completed 200 OK in 582ms (Views: 570.6ms | ActiveRecord: 0.0ms)


Started POST "/createcv" for ::1 at 2015-06-16 17:22:12 +0200
Processing by StaticPagesController#createcv as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"28oSelskM87GZ/geLj6yl3tOrtvKktH/poBasO4pyt7I2QNKxw9HX4J+yS3cmisuzmGOGnr+6IxZdh+uQGDRDQ==", "cvs"=>{"nom"=>"hjsvqsv"}, "commit"=>"Save Cvs"}
 User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Cv Load (0.0ms)  SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ?  [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (11.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.0ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 643ms (Views: 629.0ms | ActiveRecord: 1.0ms)

2 个答案:

答案 0 :(得分:1)

params.require(:cv).permit(:nom)

应该是

params.require(:cvs).permit(:nom)

因为所有参数都嵌套在:cvs而不是:cv

另外,查看您的日志和路线:

Processing by StaticPagesController#createcv

您需要将操作重命名为createcv

无论如何,你的应用程序中的路由似乎是错误的...除非你想要那样。

理想情况下,你应该这样做:

static_pages控制器中,操作createcv您将启动新的CV对象:

def createcv
  ...
  @cv = Cv.new
end

并且在createcv.html.erb中,表单将是这样的:

<%= form_for @cv do |f| %>
    Nom : <%= f.text_field :nom %><br />
    <%= f.submit %>
<% end %>

rails会知道表单中的@cv是一个新对象,它会向表单添加正确的路径,这将指向({取决于您的应用)/cvs post method。 这意味着当您提交简历时,来自create的操作cv_controller应该处理剩余的过程。 在这种情况下,您不会需要添加的路线,添加后应该在那里 resources :cvs

这只是一个可能不符合您需求的示例,因为我不知道您是如何命名您的模型,控制器等的。

答案 1 :(得分:0)

Rajarshi Das的答案很好,只是在我看来你想通过访问/ createcv来打开你的表格。所以改变您的路线:

PdfWriter.NO_SPACE_CHAR_RATIO