开发者

Rails alternative to including active record call in view

开发者 https://www.devze.com 2023-02-18 06:05 出处:网络
I have a form partial that looks like this: <%= form_for(@pool) do |f| %> <div class=\"field\">

I have a form partial that looks like this:

<%= form_for(@pool) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :tournament %><br />
    <%= f.collection_select :tournament_id, Tournament.active, :id, :name, :prompt => true %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

This seems like a code smell because the view shouldn't be responsible for knowing how to get the data for the <select> tag. The alternative to have the controller assign an instance variable is problematic because I have to replicate that code in several actions depending on whether or not this form is rendered.

In ASP.NET MVC I'd just pull that field out into a partial view and display it with a call to RenderAction Which would evaluate a common controller action. However, in Ra开发者_运维知识库ils render :action => '/view' seems to only allow full blown views to be rendered. I'm pretty new to Rails so I'm not sure about what the best practices are.


You can do a helper method as coder_tim suggests, but in my opinion that still leaves data access in the view.

The controller is the proper place for this and if you're worried about duplication, set up a before_filter that only acts on the actions that need this collection:

before_filter :get_active_tournaments, :only => [:new, :edit]

for example.

Hope this helps.


I like the smell of that code :) Simplicity over extremism. Less files = less methods to worry = cleaner code.

However, there are times when a dropdown is used too many times in your application, and it's a little more complicated than just calling a scope. In that cases, I write a helper.

0

精彩评论

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