为HABTM关联选择部分形式的语句

时间:2012-09-05 19:15:06

标签: ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many

我有两个模型ClientTopic。两者之间都有HABTM关联。

我正在尝试在我的客户端视图中的_form部分中添加一个select语句,允许用户向客户端添加主题(或编辑该主题等)。

这是我的表格部分看起来的样子:

<%= form_for(@client) do |f| %>

  <div class="field">
    <%= f.label :topic %><br />
    <%= f.select :topics, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我得到的第一个错误是:

ActiveModel::MassAssignmentSecurity::Error in ClientsController#create

Can't mass-assign protected attributes: topics

所以,在我的Client模型中,我添加了这个:

attr_accessible :email, :firm_id, :name, :phone, :topics

这是我现在得到的错误:

NoMethodError in ClientsController#create

undefined method `each' for "1":String

我的Clients控制器的创建操作非常标准:

  def create
    @client = Client.new(params[:client])

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

这些是提交的参数(注意topics正在传递 - 而不是topic_id,但topic_id也不起作用):

{"utf8"=>"✓",
 "authenticity_token"=>"J172LuZQc5NYoiMSzDD3oY9vGmxxCX0OdxcGm4GSPv8=",
 "client"=>{"name"=>"Jack Daniels",
 "email"=>"jack.daniels@some-email.com",
 "phone"=>"2345540098",
 "firm_id"=>"2",
 "topics"=>"1"},
 "commit"=>"Create Client"}

如何使用此select语句在创建客户端时将主题分配给我的客户?

谢谢!

1 个答案:

答案 0 :(得分:1)

设置“Topic”属性时,Client需要一个Topic类的实例。

由于您要传递ID,因此需要更改:

<%= f.select :topics, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>

设置topic_ids代替:

<%= f.select :topic_ids, Topic.all.collect { |topic| [topic.name, topic.id] }, {:include_blank => 'None'} %>

当然,在attr_accessible:

attr_accessible :email, :firm_id, :name, :phone, :topic_ids