【问题标题】:Rails 3 - best_in_place editingRails 3 - best_in_place 编辑
【发布时间】:2011-08-01 04:07:13
【问题描述】:

希望是一个简单的答案;我正在使用 gem best_in_place,效果很好。我试图弄清楚如何使用以下方法创建下拉菜单:

:type => :select, :collection => []

我想要做的是传入从我的用户模型中输入的名称列表。

任何想法如何做到这一点?我可以将它与 collection_select 混合使用吗?

【问题讨论】:

    标签: jquery ruby-on-rails edit best-in-place


    【解决方案1】:

    :collection 参数接受一个键/值对数组:

        [ [key, value], [key, value], [key, value], ... ]
    

    其中key选项值value选项文本

    最好在与要为其生成选项列表的对象对应的模型中生成此数组,而不是在您的视图中。

    听起来您已经启动并运行了 best_in_place,因此这里有一个项目显示页面的简单示例,您希望在其中使用 best_in_place 通过选择框更改特定项目的分配用户。

    ## CONTROLLER
    
    # GET /projects/1
    # GET /projects/1.xml
    # GET /projects/1.json
    def show
      @project = Project.find(params[:id])
    
      respond_to do |format|
        format.html
        format.xml  { render :xml => @project.to_xml }
        format.json { render :json => @project.as_json }
      end
    end
    
    
    ## MODELS
    
    class User
      has_many :projects
    
      def self.list_user_options 
        User.select("id, name").map {|x| [x.id, x.name] }
      end
    end
    
    class Project
      belongs_to :user
    end
    
    
    ## VIEW (e.g. show.html.erb)
    ## excerpt
    
    <p>
      <b>Assigned to:</b>
      <%= best_in_place @project, :user_id, :type => :select, :collection => User::list_user_options %>
    </p>
    
    # note :user_id and not :user
    

    请注意,无论值是否更改,best_in_place 的主版本都会发送 ajax 请求以获取选择框。

    还有一点要记住; best_in_place 用于“就地”编辑现有记录,而不是创建新记录(为此,在新页面的 _form 部分中使用 collection_select)。

    【讨论】:

    • 谢谢!得到这个工作......很容易错过你在示例末尾的代码,这要归功于 OS X 中的 chrome 滚动。
    • 如果它对你有帮助,也许你应该选择这个作为你的答案。
    • 感谢您的回答,一个问题是......我们如何允许在select 中选择“空白”选项?即完全 blanknone 或类似的东西。
    猜你喜欢
    • 2023-03-13
    • 2012-12-16
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多