在Rails 4中构建一个具有多对多关系的嵌套表单

时间:2013-12-18 08:13:37

标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-attributes

我有一个模型(用户),has_many另一个模型(专业) - 这应该由表单中的一个(或多个)选择菜单表示。

我无法理解选择菜单无法渲染的原因?我是以错误的方式构建选择助手吗?或者在视图或控制器中出现其他问题?用户的name属性在表单中显示正常。


模特:

class User < ActiveRecord::Base
  has_many :occupations, dependent: :destroy
  has_many :professions, through: :occupations
  accepts_nested_attributes_for :occupations
end

class Profession < ActiveRecord::Base
  has_many :occupations, dependent: :destroy
  has_many :users, through: :occupations
end

class Occupation < ActiveRecord::Base
  belongs_to :user
  belongs_to :profession
end

控制器:

def edit
end

def create
  @user = User.new(user_params)

  if @user.save
    redirect_to @user, notice: 'User was successfully created.'
  else
    render action: 'new'
  end
end

private
  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:name, :email, ocuppations_attributes: [:id, :user_id, :profession_id])
  end

视图(压缩):

<%= form_for(@user) do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :occupations do |builder|  %>
    <%= builder.select :profession_id, Profession.all.collect {|x| [x.title, x.id]} %>
  <% end %>
<% end %>

1 个答案:

答案 0 :(得分:0)

不应该是一个集合选择?

<%= builder.collection_select(:profession_id, Profession.all, :id, :title) %>