2012-09-05 25 views
0

我有兩個型號ClientTopic。它們之間都有HABTM關聯。以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_idtopic_id也不管用)的PARAMS:

{"utf8"=>"✓", 
"authenticity_token"=>"J172LuZQc5NYoiMSzDD3oY9vGmxxCX0OdxcGm4GSPv8=", 
"client"=>{"name"=>"Jack Daniels", 
"email"=>"[email protected]", 
"phone"=>"2345540098", 
"firm_id"=>"2", 
"topics"=>"1"}, 
"commit"=>"Create Client"} 

如何在使用此select語句創建客戶端時獲得分配給我的客戶端的主題?

謝謝!

回答

1

設置「主題」屬性時,客戶端需要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 
+0

啊。 ..當然。完善。 Rails指南對這些細節有點輕鬆,不是嗎?還是我在某個地方想念它? – marcamillion

+0

該指南的部分內容絕對不在您的面前: http://guides.rubyonrails.org/association_basics.html#has_many-association-reference 請參閱「4.3.1.6 collection_singular_ids = ids」 –

+0

Yeh ..這很愚蠢。當我抽出時間時,我會舉一些例子,看看他們是否會接受它。再次感謝! – marcamillion