2012-03-20 125 views
1

我想在新的地方插入標籤。給這個標籤是不同的模型。has_many記錄插入

####### models ########## 
class Tag < ActiveRecord::Base 
    belongs_to :place 
    attr_accessible :tag 
end 

class Place < ActiveRecord::Base 
    has_many :tags 
end 

我該如何處理這個新的Place創建表單?和places_controller中的創建操作?這樣我可以插入新的位置和標記標籤,然後將產品標識分配給每個標籤。

####### place controller ########## 

def create 
    @place = Place.new(params[:place]) 
    @tag = Tag.new(params[:?????]) #this should be more than once 

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

####### place new form ########## 
<%= form_for @place do |f| %>  
    <div class="field"> 
    <%= f.label :title %><br /> 
    <%= f.text_field :title %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br /> 
    <%= f.text_area :description %> 
    </div> 
    <div class="field"> 
    <%= f.label :rank %><br /> 
    <%= f.text_field :rank %> 
    </div> 
    <div class="field"> 
    <%= f.label :lat %><br /> 
    <%= f.text_field :lat %> 
    </div><div class="field"> 
    <%= f.label :lng %><br /> 
    <%= f.text_field :lng %> 
    </div> 
    <div class="field"> 
    <%= f.label :address %><br /> 
    <%= f.text_area :address %> 
    </div> 
    <div class="field"> 
    <%= f.label :website %><br /> 
    <%= f.text_field :website %> 
    </div> 
    <div class="field"> 
    <%= f.label :phone %><br /> 
    <%= f.text_field :phone %> 
    </div> 
    <div class="field"> 
    <%= label_tag "tags" %> 
    <%= f.text_field :tag %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

回答

1
  1. 如果你想這樣做你自己,你應該看看accepts_nested_attributes_for,那裏是一個偉大的2部分教程由Ryan貝茨在railscasts.com

  2. 如果你不想自己做,有幾個標籤寶石可用,例如: ActsAsTaggableOn

0

在你的窗體添加此:

<%= f.fields_for :tags do |t| %> 
    <%= t.label :name %> 
    <%= t.text_field :name %> 
<% end %> 

而在你Place型號:

accepts_nested_attributes_for :tags 

而在你的控制器,你甚至不必擔心創建標籤。

您應該仍然嘗試閱讀大約fields_foraccepts_nested_attributes_for,它們通常很有用,因爲您的問題非常普遍。