2012-03-20 2 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으로 계속 읽어야합니다. 문제는 매우 일반적이므로 유용합니다.