Rails:Collection_select将ID保存为一个条目

时间:2012-10-04 09:39:59

标签: ruby-on-rails ruby database controller

我正在尝试使用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)

Ross的更新:

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} ) 

1 个答案:

答案 0 :(得分:1)

使用

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