2012-03-20 19 views
1

新しい場所にタグを挿入したいと思います。そのタグに異なるモデルがあることを示します。has_manyレコード挿入

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

class Place < ActiveRecord::Base 
    has_many :tags 
end 

新しいプレイスフォームを作成するにはどうすればよいですか? places_controllerのアクションを作成しますか?新しい場所とmantタグを挿入して、各タグにプロダクトIDを割り当てることができます。

####### 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. 自分でそれをしたい場合は、あなたがしたくない場合はrailscasts.com

  2. でライアンベイツによって偉大な2パートのチュートリアルがありますaccepts_nested_attributes_for、になるはずですあなた自身でそれをやってください。例えば、 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を読んでみてください。問題は非常に一般的なので、しばしば役に立ちます。