views:

40

answers:

1

I have a widget for currencies which I use throughout my application. Ie. the user changes the currency from EUR -> USD, or about 13 other currencies. I have a few other use-cases such as dates but this one is the easiest to explain. Currency basically just updates a session variable by calling the currency controller and then uses some JS to reload the page, but I'd like to only fetch certain elements of the page (ie that reflect the currency change and nothing else)...

$("#places_list").html("<%= escape_javascript(render :partial => 'places/list') %>");

or if another controller

$("#locations").html("<%= escape_javascript(render :partial => 'locations/places') %>");

but these elements are specific to the current controller, ie rendering a controller specific partial such as a list... (the currency math itself is in a an application helper, so no new logic is going on), and the currency controller is simple a partial loaded by different controllers. (Locations, Places, etc)

Other than making an action in every controller specific for this purpose, how can I make it behave in a way that I can render elements specific to the current controller, so I can replace them intelligently over js, instead of reloading? Ie. I can pass in to currency the current controller

<%= hidden_field_tag :info, controller.controller_name %>

I'm not sure if any of that makes sense, but I hope it does, at least in my own brain if not in anyone else's.

A: 

Hi holden

I have tried a little app and below would be a one solution for you,

first of all, in my case what I'm trying to do is to have an attribute called :info in each model , so that I can call it (<%= f.text_field :info %>) in my views (please note f can be any instance of a model)

for that I need to add :info attribute to each model. You have several ways of doing it

1 - create a class (which inherits from AR::Base and inherit all the other models from the given class) (but it requires some code changes)

2 - Quick and ugly way is to inject my :info attribute to AR::Base class (Which I did ;) )

create a file in config/initializers say curreny.rb and add this code

module ActiveRecord
 class Base
   attr_accessor :info
 end
end 

after that from any view which u uses AR, will have the :info attribute

Ex: users/new

New user

<% form_for(@user) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :info %><br />
    <%= f.text_field :info %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', users_path %>

Please note: this is not a very good solution, but I think with this you can start thinking

cheers

sameera

sameera207