ruby-on-rails - rails : Share variables between controller and view

标签 ruby-on-rails ruby

<分区>

Possible Duplicate:
Passing only two variables between controller and view - best practice?

这是我的 Action :

  def list
    @codes = Code.order("created_at")
    @languages = Language.order('name').collect {|l| [l.name, l.coderay]}
  end

这是我的看法(我删除了一些行):

<% @codes.each do |code| %>
    <div class="code">
        <%= link_to code.title, :action => 'show', :id => code.id %>
        <% if  code.author %>
            @<%= code.author %>
        <% end  %>
    </div>
<% end %>
<%= render :partial => 'shared/error_messages', :locals => {:object => @code} %>
<%= form_for :code, :url => {:action => 'create' }, :html => {:multipart => true} do |f| %>
    <%= f.text_field :title %><br />
    <%= f.text_area :content %><br>
    <%= f.select(:language, @languages, {:selected => 'text'}) %>
    <%= f.text_field :author %><br>
    <%= f.submit "Submit code" %>
<% end %>

里面有3个变量:@codes(帖子列表),@code(当前帖子,在另一个 Action 中使用)和@languages。

我的 IDE 写道:

At most two instance variables should be shared between controller and view
This inspection warns if there are more than two instance variables shared between a controller and a view. A controller should only manage one instance variable, plus a second one for the current_user variable.

通常我在 Controller 和 View 之间共享更多变量(在 PHP 中),有时会超过 10 个。
在 Rails 中是如何完成的?

最佳答案

您可以通过使语言成为助手来保存实例变量:

def languages
  Language.order('name').collect {|l| [l.name, l.coderay]}
end

关于ruby-on-rails - rails : Share variables between controller and view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277420/

相关文章:

ruby-on-rails - Rails 缓存清扫器

ruby-on-rails - 有没有一种方法可以获取过滤器的点击次数,而无需返回过滤器的所有结果

ruby-on-rails - rails has_many :through has_many :through

ruby - 无法使用 ruby​​ 2.3.0 评估 Rubymine 中的 HTML 元素

ruby-on-rails - Ruby on Rails Controller WHERE 语句

ruby-on-rails - 使用 Rails/Active Record 的时间数据

ruby-on-rails - 仅当特定实例变量具有值时,如何 stub 实例方法?

ruby-on-rails - 使用 RSpec 改进的测试类

ruby-on-rails - Rails Checkout SSL heroku

javascript - 将二维数组从 ruby​​ 传递到 javascript