开发者

A Good Design Pattern for Ruby on Rails with Ajax for the following scenario?

I have two models A and B where updating B in some cases causes updates to A as well (done in model code). Now, in my UI, I want to display A and B in same page and can have their own operations (e.g. update some field in them). I don't want to reload the whole page on any update.

My question is: I w开发者_JAVA百科ould like to put UI code for A and B separate and I don't want to have code in A or B referencing the other. Is it possible to have a design for this requirement? Thanks.


Ok so the question is: The controller for A's update should not know about B and vice versa, yet the page should update B.

My point would be have the PAGE do a request to A controller to do work. Then after a successful round trip request B for changes (or re-rendering). Its 2 trips.

Or you can have an rjs respond in the A and B controller indicating that both parts of the page are to be updated, without having A or B model aware of each other.


Most of the Rails helpers assume you're just going to update a specific section in the page. The most straight forward and least efficient way to do it is to expand the scope of “specific section” to include both the view elements for A-records and B-records. (Which could be the entire page, as you mention.)

More efficiency will likely involve more complexity as well. I'd say this holds true for my answer too.

My immediate thought here is a generic event mechanism. You basically issue your AJAX call to update as usual, and the response contains multiple return values that contain updates for specific A or B records. For example:

{ "A": [
    { "id": 23, "content": "<span>name:</span> Apples" },
    { "id": 52, "content": "<span>name:</span> Oranges" }
  ],
  "B": [
    { "id": 10, "content": "<span>name:</span> Fruits" }
  ]
}

Then, AJAX calls for updates to both A and B-records are issued, and their responses are handled by a single JavaScript function. That single function then takes care of dispatching the update to the separate view components you want. Think of it as a simple event handler.

The simplest way to implement this is probably to have each view component register itself with an 'update' function on page load. Your event handler then calls all of these with the JSON object. The update functions then take what they want, update the specific elements they manage, and you're set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜