对于rails 4.0.1中的新记录,"没有将符号显式转换为字符串"(仅限)

Mic*_*ant 8 ruby rspec ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

在我的rails 4升级之后,尝试为我的任何ActiveRecord类创建一个新记录

No explicit conversion of Symbol into String
Run Code Online (Sandbox Code Playgroud)

例如,这是我的链接links_params方法

def link_params
  params.require(:link)
  .permit(:url_address, :group_id, :alt_text, :version_number, 
  :position, :content_date, :verified_date) # This is line 157
end

# line 118 is: @link = Link.new(link_params)
Run Code Online (Sandbox Code Playgroud)

但我明白了

TypeError (no implicit conversion of Symbol into String):
  app/controllers/links_controller.rb:157:in `link_params'
  app/controllers/links_controller.rb:118:in `create'

This error occurred while loading the following files:
link

Parameters:

{"utf8"=>"?",
 "authenticity_token"=>"0FqFTx2EjCIO+R+rm97lF15+id4b452n+dBuUNxAL9U=",
 "link"=>{"url_address"=>"http://www.google.com",
 "alt_text"=>"",
 "version_number"=>"",
 "group_id"=>"49",
 "content_date"=>"08/18/2014"},
 "commit"=>"Save"}
Run Code Online (Sandbox Code Playgroud)

JTG*_*JTG 11

我不确定它是怎么发生的,但看起来你的params对象只是一个哈希...而不是一个ActionController::Parameters对象.当params只是一个哈希:

params = {"utf8"=>"?", "authenticity_token"=>"0FqFTx2EjCIO+R+rm97lF15+id4b452n+dBuUNxAL9U=", "link"=>{"url_address"=>"http://www.google.com", "alt_text"=>"", "version_number"=>"", "group_id"=>"49", "content_date"=>"08/18/2014"}, "commit"=>"Save"}

params.require(:link)
=> TypeError: no implicit conversion of Symbol into String

params.class
=> Hash
Run Code Online (Sandbox Code Playgroud)

但如果它是一个ActionController :: Parameters对象

params2 = ActionController::Parameters.new({"utf8"=>"?", "authenticity_token"=>"0FqFTx2EjCIO+R+rm97lF15+id4b452n+dBuUNxAL9U=", "link"=>{"url_address"=>"http://www.google.com", "alt_text"=>"", "version_number"=>"", "group_id"=>"49", "content_date"=>"08/18/2014"}, "commit"=>"Save"})

params2.require(:link)
=>{"url_address"=>"http://www.google.com", "alt_text"=>"", "version_number"=>"", "group_id"=>"49", "content_date"=>"08/18/2014"} 

params2.class
=>ActionController::Parameters
Run Code Online (Sandbox Code Playgroud)

你在做的东西params之前link_params得到它的持有?

编辑:根据API文档,强params只在Rails 4.0.2中可用.如果您使用的是早期版本,则必须坚持使用Rails 3 attr_accessible

  • 我的意思是,你可以在过滤之前放置`params = ActionController :: Parameters.new(params)`.但是你已经没有为这个对象提供服务真是奇怪了.... (2认同)