【问题标题】:Rails: Collection_select saving IDs as one entryRails:Collection_select 将 ID 保存为一个条目
【发布时间】:2012-10-04 09:39:58
【问题描述】:

我正在尝试使用 collection_select 而不是 select。

<%= form_for(@technol) do |tech| %>
  <div class="field">
    <%= tech.label :tech %><br />
    <%=  tech.select(:tech, Technol.all.map {|p| [p.tech]}.uniq,:prompt => "Select a previous role") %>
  </div>
<%end%>

此代码有效,允许我将一项技术链接到一个项目。我试过这样做:

<%= form_for(@technol) do |tech| %>
   <div class="field">
    <%= tech.label :tech %><br />
    <%= tech.collection_select(:tech,  Technol.all, :id, :tech, {}, {:multiple => true} ) %>
  </div>
<%end%>

collection_select 出现,所有技术都显示在下拉列表中,当我选择一些并提交项目时,这些技术显示为一个条目,通过它们的 ID。

--- - '' - '11' - '12' - '13'

这是我认为导致问题的创建操作:

def create
    @project = Project.new(params[:project])
    @technol = Technol.new(params[:tech])

    params[:technol].each_value do |tech|

    technology = Technol.find_or_create_by_tech(tech)

    @project_technol = @project.projecttechnols.build(:technol_id => technology.id) 
end

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render json: @project, status: :created, location: @project }
      else
        format.html { render action: "new" }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

我认为我的循环方式有问题。希望有人能看到。我是 Rails 新手,所以在尝试帮助我时请记住这一点。提前致谢。

更新

我已尝试将 collection_select 更改为:

<%=  tech.select(:technol, :id, Technol.all.map {|p| [p.tech]}.uniq,:prompt => "Select a previous role") %>

我得到了这个错误。 wrong number of arguments (7 for 6)

罗斯更新:

wrong number of arguments (7 for 6)
Extracted source (around line #273):

273: tech.collection_select(:tech, :tech_ids, Technol.all, :id, :tech, {:prompt => "Select a previous role"}, {:multiple => true} ) 

【问题讨论】:

  • 我认为它的语法是 collection select try tech.collection_select(:tech, :tech_ids, Technol.all, :id, :tech, {}, {:multiple => true} )跨度>
  • 您好,我收到的错误与我的问题中的更新相同。
  • 使用正确的括号,尝试复制粘贴和我上面评论的一样

标签: ruby-on-rails ruby database controller


【解决方案1】:

使用

collection_select(:test, :tech_ids, Technol.all, :id, :tech, {:prompt => "Select a previous role"}, {:multiple => true} ) 

【讨论】:

  • 我刚刚更新了我的问题,向您展示运行您的代码时会发生什么。干杯
  • 我收到无方法错误。 undefined method "tech_ids" for #&lt;Technol id: nil, tech: nil, created_at: nil, updated_at: nil&gt;。所以我把它改成了:id,我没有在项目中添加任何技术`
猜你喜欢
  • 2019-07-20
  • 2012-04-25
  • 2019-09-07
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
相关资源
最近更新 更多