What's the best way to do UJS in rails when you have a re-usable widget? -
in current project have couple instances have re-usable form exists inside rails partial. form submits specific controller via ajax (:remote => true). controller stuff , returns appropriate js.erb modify page via javascript.
this works fine when have single view. problem seems happen when re-usable partial exists on multiple views. in view 1 might want issue different set of javascript commands in view 2.
as concrete example, have comments controller has normal crud operations.
i have partial called _comments_box.erb. _comments_box.erb contains ability submit comment via simple line:
- form_for comment, :url => post_comments_path(post), :remote => true |f|
this submits comments_controller.rb create method looks somethings this:
def create ... stuff, create new comments model respond_to |format| # respond create.js.erb format.js end end
the create.js.erb in turn adds comment view, perhaps doing bunch of other updates dom.
say render _comments_box.erb within view called post_summary.erb. have view, post_detail.erb requires same _comments_box.erb. post_detail.erb requires me update different divs on dom in response new comment.
i need create different js response each instantiation. can either:
- create alternate controller method, create_2. pass in parameter _comments_box.erb post_detail.erb _comments_box.erb partial knows controller method fire. allow me have separate file _create_2.js.erb allow me manipulate post_detail.erb view independently.
- forget using js.erb altogether , use plain old ajax , json, , handle javascript manipulation on client-side.
it seems option 1 allows me continue use ujs supported rails nice. means adding lot of duplicate code everywhere annoying. there way me elegantly while continuing use ujs?
i'd not recommend using ujs frontend apps: server shouldn't take care of client side business. agree it's useful , clean lacks performance , should kept backend stuff (rjs move gem, see here: http://weblog.rubyonrails.org/2011/4/21/jquery-new-default).
that said, solutions expose:
1) think won't need controller, you'd have pass additional params in order know query came from.
hidden_field
trick. info, renderjs.erb
fileformat.js { if condition render "create.js.erb" else render "create_2.js.erb" end }
2) i'd go , return json you'll face same problem: knowing request comes from.
Comments
Post a Comment