Ruby on Rails Wednesday, May 18, 2016



On May 18, 2016 at 03:17:10, Colin Law (clanlaw@gmail.com) wrote:

On 18 May 2016 at 08:51, Alessio Varalta <lists@ruby-forum.com> wrote: 
> Hi, if I try params.inspect i see 
> 
> {"utf8"=>"✓", 
> 
> "authenticity_token"=>"RvpwQw/RdTAT2d4jtaSyBAYRgT1mKgWg9kyrS7pUnMo=", 
> "person"=>{"birthplace"=>{"it"=>"Padova", "de"=>"Padovan"}}, 
> "commit"=>"Create Person", "action"=>"create", "controller"=>"people"} 
> 
> 
> So I think is correct but in database i have 
> 
> --- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\nit: Padova\nde: 
> Padovan\n 

I have just realised what you are trying to do. Are you trying to 
save a hash object in a field in the database? I have never done that 
as almost always you are better to use models and associations for 
storing the data. That is the Rails way. If you really need to do 
that then google for how to save a hash in the database using rails, 
for how to use serialisers to do it. 

Colin 


Postgresql 9.2 has JSON objects, 9.4 introduces JSONB, but they are often more hassle than they are worth. See the Postgresql docs.

ActiveRecord can also serialize/deserialze hashs (or any other sort of Ruby non-primitive), but it's also often more hassle than it's worth. See http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize for the latter. 

I'll very much second Colin's first point: more analysis and better understanding of the data structures generally give better results. (i.e., more testable, extendable, maintainable, to my mind)

No comments:

Post a Comment