【问题标题】:Ruby on Rails: How to use a local variable in a collection_selectRuby on Rails:如何在 collection_select 中使用局部变量
【发布时间】:2010-04-20 15:06:12
【问题描述】:

我正在尝试使用 collection_select 方法创建一个

因此,当我为productcategories 创建

_product_row.erb(不工作):

My product: <%= product.name %>
<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>

截图:

alt text http://img534.imageshack.us/img534/8929/screenshot20100421at120.png

我发现我可以通过事先声明一个实例变量来使其工作,但这对我来说似乎是一个巨大的黑客攻击。

_product_row.erb(工作):

<% @product_select_tmp = product %>
<%= collection_select(:product_select_tmp, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>

截图:

alt text http://img534.imageshack.us/img534/1958/screenshot20100421at120l.png

因为这个部分是迭代产品的集合,我不能只在控制器中声明@product(IOW,除非我遗漏了一些东西,product 必须是这个的局部变量部分)。

那么当使用局部变量调用collection_select时,如何让collection_select选择合适的项目呢?

【问题讨论】:

    标签: ruby-on-rails form-helpers


    【解决方案1】:

    您是否尝试过在选项哈希中传递:selected 键?如果您为它提供当前的product.id,它的行为应该符合您的预期。

    &lt;%= collection_select(:product, :category_id, @current_user.categories, :id, :name, {:prompt =&gt; "-- Select a category --", <strong>:selected =&gt; product.category.id</strong>}) %&gt;

    【讨论】:

    • 我想我会添加这个作为它自己的答案,因为最后一个似乎本身就很有用,尽管不是你想要的。
    • 再次感谢 Damien,这似乎成功了,尽管它应该是 :selected => product.category.id。如果您更新答案,我会将其标记为已接受。值得注意的是,在这种情况下, :prompt 选项仍将出现在下拉列表中(如果您使用我问题的第二个示例中的方法,rails 足够聪明,可以将其排除在选项之外),但我可以接受:)
    【解决方案2】:

    您可以将集合传递给局部变量,并指定一个局部变量将它们传递为:

    <%= render :partial => "products/product_row", :collection => @products, :as => :products %>
    

    相关文档:http://apidock.com/rails/ActionView/Partials

    【讨论】:

    • 您想要一种无需显式声明即可获取实例变量@products 的方法,对吗?通过render :partial ... :collection =&gt; @collection 传递所需的集合应该可以解决问题。如果您想在每个产品表行中有一个下拉列表,您将需要整个集合。还是我误解了这个问题?
    • 不,我希望能够使用 local 变量而不是实例变量调用 collection_select,并在生成的 HTML 中选择正确的选项。对不起,我意识到这个问题有点令人困惑。也许我会尝试重新措辞。
    • 哦,好吧,如果是这种情况,您只需致电render :partial ... :collection =&gt; @collection, :as =&gt; :local_variable。我会相应地更新我的答案。
    • 嗨,Damien,谢谢,我不知道您可以使用这样的集合渲染部分内容!很棒的小费。虽然它仍然没有解决问题。我重新措辞了我的问题,希望能更清楚。
    猜你喜欢
    • 2016-08-23
    • 2015-12-10
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多