Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't convert Symbol into String

I have the following code in Ruby, take directly from the Getting Started with Rails guide

 def create
  @post = Post.new(post_params)

  @post.save
  redirect_to @post
end

private
  def post_params
    params.require(:post).permit(:title, :text)
  end

When I run the above Create I get the following error.

can't convert Symbol into string

like image 555
Ravi Prakash Singh Avatar asked Jul 02 '13 10:07

Ravi Prakash Singh


People also ask

Which symbol does not have the ability to convert any values to string?

Unlike Java, the '+' does not automatically convert numbers or other types to string form. The str() function converts values to a string form so they can be combined with other strings.

How do I convert a symbol to a string in Ruby?

Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.

What are symbols in Ruby?

What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource. A resource can be: a method.


2 Answers

It seems like you are trying to use strong paramaters. You get this error cannot convert symbol into string because you have not configured the strong_parameters. So by default you cant use require on params with symbols.

Configure strong parameters as follows:

1.) Add gem 'strong_parameters' to your gemfile and bundle it.
2.) Include Restrictions to you model as follows.
       include ActiveModel::ForbiddenAttributesProtection to your model.
3.) Disable white listing in application confiuration(config/application.rb)
    config.active_record.whitelist_attributes = false

See the documentation for more details on configuring.

Now your code should work.

like image 160
Amarnath Krishnan Avatar answered Sep 28 '22 07:09

Amarnath Krishnan


If anyone is using Mongoid, you can fix this issue by adding the following to an initializer:

Mongoid::Document.send(:include, ActiveModel::ForbiddenAttributesProtection)
like image 25
Ben Yee Avatar answered Sep 28 '22 06:09

Ben Yee