ruby on rails - Pass a PORO from view to controller -


what best way pass plain old ruby object have in view controller method?

it not object persisted in db. rather not refactor things , want ideas on best way pass object.

view

link_to "activate", activate_apis_path(my_ip_instance: @my_ip), class: "btn btn-primary btn-xs" 

controller

@my_ip = params[:my_ip_instance] 

@my_ip string... want whole object

(rails 4.2)

usually best way through form. consider creating form hidden fields of @my_ip attributes.

<%= form_tag activate_apis_path %>   <%= hidden_field_tag "my_ip_instance[foo]", @my_ip.foo %>   <%= hidden_field_tag "my_ip_instance[tomato]", @my_ip.tomato %>   <%= submit_tag "activate", class: "btn btn-primary btn-xs" %> <% end %> 

(extra credit: loop on @my_ip's attributes generate hidden fields.)

another way serialize @my_ip json , deserialize in controller. think messier though.

link_to "activate", activate_apis_path(my_ip_instance: @my_ip.to_json) 

to make work more complex object, need write own serializer/deserializer logic class described in this post.

require "json"  class   def initialize(string, number)     @string = string     @number = number   end    def to_json(*a)     {       "json_class"   => self.class.name,       "data"         => {"string" => @string, "number" => @number }     }.to_json(*a)   end    def self.json_create(o)     new(o["data"]["string"], o["data"]["number"])   end end 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -