简体   繁体   中英

How best to render different partials in a view in ruby on rails

I'm quite new to rails and I don't have a very good sense of where to put things yet. I have a view which has a few buttons, each of which will render a different graph or form but I'm not sure where to put the logic for the rendering.

So far I've considered the following:

  1. Adding some methods to my controller which render a js.erb that puts the relevant graph in an empty div. The problem with this is that my controller will get quite busy, which I think goes against the rails style.
  2. Having a javascript function linked to the buttons onclick event which just puts the puts the partial in the div. The issue with this is that I will have all of the pre-rendered graphs lying around and it seems quite messy.

You should have one or more controller actions that render this. It's fine to have many actions in a controller - what you want to avoid is having very big actions. An action should usually be very concise: grab the relevant data from the relevant model, and then render something.

Set a value or id for each button or form and set yours onclick funtions with Ajax get calls. So, in the data param, send the buttons or forms values/IDs, where values/IDs Will be a partial (graph or forms). Finally, in some action, receive those params and interpolate it in render partial, like this:

def graphs 
  render partial: "path/to/partial/#{params[:button_id]}"
end

Now you can populate divs with ajax success.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM