View Full Version : Passing parameters from Ruby to JS.

18 Jun 2007, 3:31 AM

I am using Ext Grid to draw a table.

"show.rhtml" page allows to access account data so the url look like
http://<server_name>/<project_name>/show/1, where 1 is an account id.

"show.rhtml" has the following code:

<%= javascript_include_tag "grid.js" %>
<div id="grid" style="border:5px solid #99bbe8; overflow:hidden; width:

"grid.js" is used for grid initialization and rendering it accesses
the "<project_name>/grid_data" method that is in the project

"grid_data" method forms the jsondata for the grid.

The problem: "grid.js" has no idea for what account the grid is
rendered. However, the account id is required in "grid_data" method to
provide a proper json data. How do I pass account id from "show.rhtml"
to "grid.js"?

Thanks for your help.

18 Jun 2007, 3:57 AM
You could do a couple of things:
1) Have your Ruby code actually render your javascript
2) Have your Ruby code render a hidden field with your proposed value. In your grid code, get the parameter from this field and pass it to your grid callback as a parameter.

2 is probably preferable for your case.

18 Jun 2007, 4:57 AM
imo the most clean and reusable way would be to encapsulate your grid.js into a custom object class and pass all params after creating an instance of it, this way you'll have all possibilities to reuse your code multiple times on the same page.

so the code would look s.th. like this:

<%= javascript_include_tag "grid.js" %>
<div id="grid" style="border:5px solid #99bbe8; overflow:hidden; width:
var myGrid = new GridHelper();
myGrid.container = 'grid';
myGrid.id = <%= params[:id].to_i || 0 %>;

hardwiring the code to look for a hidden field is a quite bad idea.

24 Jun 2007, 4:53 AM
Very helpful. Thanks a lot.

18 Jul 2007, 4:46 AM
Now in the opposite direction...

Imagine I have an EXT grid with inline editing. So I need to pass user entered data to RoR in order to update database. What is the most convenient way to do it?

P.S. A lot of data.

18 Jul 2007, 5:03 AM