【问题标题】:Rails- in place editing using best_in_place gem for an array collection defined in model itselfRails- 使用 best_in_place gem 对模型本身定义的数组集合进行就地编辑
【发布时间】:2012-07-27 23:01:22
【问题描述】:

我看到RailsCasts#302 描述了使用 best_in_place gem 进行就地编辑。那里的性别选项 Ryan 使用 show.html.erb 中的数组并将其设为下拉框(请参阅他明确定义数组的性别部分)。

<p>
  <b>Gender:</b>
  <%= best_in_place @user, :gender, type: :select, collection: [["Male", "Male"], ["Female", "Female"], ["", "Unspecified"]] %>
</p>

但我想要的是我在模型本身内部定义了一个数组,例如:(因为我的数组元素并不简单且数量少)

例如:

user.rb

class User < ActiveRecord::Base
  def authencity_types
    ['Asian', 'Latin-Hispanic', 'Caucasian']
  end
end

我将如何使用 best_in_place 语法将此数组元素用作下拉列表。

PS:我确实尝试过这样的事情

<% @users.each do |user| %>
  <%= best_in_place user, :authencity, type: :select, :collection => User::authencity_types  %>
<% end %>

但它说的是未定义的方法 authencity_types

【问题讨论】:

    标签: ruby-on-rails-3 inplace-editing best-in-place


    【解决方案1】:

    你在 User 模型上定义了一个实例方法,所以试试这个。

    <% @users.each do |user| %>
      <%= best_in_place user, :authencity, type: :select, :collection => user.authencity_types  %>
    <% end %>
    

    或者,您可以将其定义为这样的类方法。

    class User < ActiveRecord::Base
      def self.authencity_types
        ['Asian', 'Latin-Hispanic', 'Caucasian']
      end
    end
    

    或者,如果它不需要是动态的,您可能需要考虑使用常量。

    【讨论】:

    • 成功了!非常感谢瑞恩! :) 我知道有非常小的基本问题困扰着我..但很困惑。
    • 由于某种原因,它只显示第二个字符或每个数组,所以我将我的数组设置为数组数组并且它有效。 [['Asian','Asian'], ['Latin-Hispanic','Latin-Hispanic'], ['Caucasian','Caucasian']]
    猜你喜欢
    • 2013-03-06
    • 2017-10-17
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2012-03-26
    • 2012-09-27
    • 2011-08-01
    • 1970-01-01
    相关资源
    最近更新 更多