即使存在,表单提交的传递参数也不会保存到数据库中

时间:2018-02-11 12:22:13

标签: ruby-on-rails ruby ruby-on-rails-5

我是Rails的新手,我正在尝试保存到数据库的链接,但是当我提交链接时,只保存时间戳。如果我尝试在我的控制器中使用require它会说它是空的,这让我更加困惑。 这是否与惯例相关我打破哪个Rails不喜欢?

index.html.erb

<%= form_for WatchedLink.new, url: {action: "create"}, html: {class: "links_to_be_scraped"} do |f| %>
  <%= f.text_field (:link) %>
  <%= f.submit "Save" %>
<% end %>

page_to_be_scraped_controller.rb

class LinksToBeScrapedController < ApplicationController

  def index     
    @watched_links = WatchedLink.all
  end

  def show
    @watched_links = WatchedLink.find(params[:id])

  end

  def new
    @watched_links = WatchedLink.new


  end

  def create

    @link = WatchedLink.new(params.permit(:watched_link))

    if @link.save 
      puts "ADDED TO THE DATABASE #{params[:watched_link]}"
    else
      puts "FAILED TO ADD TO THE DATABASE"
    end
  end

  def edit

  end

  def upadate

  end

  def delete

  end

  def destroy

  end
end

日志

Started POST "/links_to_be_scraped" for 127.0.0.1 at 2018-02-11 03:19:04 +0000
Processing by LinksToBeScrapedController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"jMv4C+k0OSkgDAj/Rw6UcZX9hFZHhbG6P4Dcb/2oyeybnVRtuOqscQZEON0rjG0Q/s6Bp6zBlUQIsVEnL5ikiw==", "watched_link"=>{"link"=>"www.google.com"}, "commit"=>"Save"}
Unpermitted parameters: utf8, authenticity_token, watched_link, commit
   (0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO `watched_links` (`created_at`, `updated_at`) VALUES ('2018-02-11 03:19:04', '2018-02-11 03:19:04')
   (66.5ms)  COMMIT
ADDED TO THE DATABASE {"link"=>"www.google.com"}
No template found for LinksToBeScrapedController#create, rendering head :no_content
Completed 204 No Content in 108ms (ActiveRecord: 66.7ms)


Started GET "/" for 127.0.0.1 at 2018-02-11 03:19:06 +0000
Processing by LinksToBeScrapedController#index as HTML
  Rendering links_to_be_scraped/index.html.erb within layouts/application
  WatchedLink Load (0.3ms)  SELECT `watched_links`.* FROM `watched_links`
  Rendered links_to_be_scraped/index.html.erb within layouts/application (9.0ms)
Completed 200 OK in 22ms (Views: 20.6ms | ActiveRecord: 0.3ms)

1 个答案:

答案 0 :(得分:1)

您发送带有参数{ watched_link: { link: ... } }的表单,但在您的控制器中,create无法访问watched_link。

更新表单中text_field标记助手的名称:

<%= form_for WatchedLink.new, url: { action: "create" }, html: { class: "links_to_be_scraped" } do |f| %>
  <%= f.text_field :link %>
  ...
<% end %>

在你的控制器中:

@link = WatchedLink.new(params.require(:watched_link).permit(:link))

您可以将create中使用的新参数移动到强params定义,例如:

private

def watched_link_params
  params.require(:watched_link).permit(:link)
end

然后您可以将创建操作更新为:

@links = WatchedLink.new(watched_link_params)

另请考虑查看ActionController::StrongParameters