2017-10-02 15 views
0

두 모델 HotelRoom이 있습니다. 새로운 호텔과 객실을 추가 할 수있는 양식을 만들고 싶습니다. 호텔의 이름과 객실 수를 나타냅니다. "중첩 된 양식"을 사용해야한다는 것을 알고 있지만 적절하게 구현하기가 어렵습니다. 여기 폼 필드로 다른 모델의 수량을 생성하는 폼

내 코드입니다 :

HotelsController

class HotelsController < ApplicationController 

    def index 
    @hotels = Hotel.all 
    end 

    def new 
    @hotel = Hotel.new 
    end 

    def create 
    @hotel = Hotel.new(hotel_params) 

    if @hotel.save 
     redirect_to @hotel 
    else 
     render 'new' 
    end   
    end 

    def show 
    @hotel = Hotel.find(params[:id]) 
    end 

    def destroy 
    @hotel = Hotel.find(params[:id]) 
    @hotel.destroy 
    redirect_to hotels_url, notice: 'Hotel was successfully destroyed.' 
    end 

    private 

    def hotel_params 
    params.require(:hotel).permit(:name, :rooms_count) 
    end 
end 

호텔 모델

class Hotel < ApplicationRecord 
    has_many :rooms, dependent: :destroy 
    accepts_nested_attributes_for :rooms 
end 

룸 모델

class Room < ApplicationRecord 
    belongs_to :hotel, optional: true # avoiding rails 5.2 belongs_to error 
end 

형태

<%= form_with scope: :hotel, url: hotels_path, local: true do |form| %> 
    <p> 
    <%= form.label :name %><br> 
    <%= form.text_field :name %> 
    </p> 

    <p> 
    <%= form.label :rooms_count %><br> 
    <%= form.number_field :rooms_count %> 
    </p> 

    <p> 
    <% form.fields_for :rooms do |f|%> 
     <p> 
     **THE CODE** 
     </p> 
    <% end %> 
    </p> 

    <p> 
    <%= form.submit %> 
    </p> 
<% end %> 

답변

0

나는 내 질문에 대한 해결책을 찾았습니다.

def create 
    @hotel = Hotel.new(hotel_params) 
    @hotel.rooms_count.times do 
     @hotel.rooms.build 
    end 

    if @hotel.save 
     redirect_to @hotel 
    else 
     render 'new' 
    end   
    end 

이 방에 입력 한 번호가 양식 필드를 계산 @ hotel.rooms_count 같은 @의 hotel.rooms.build 많은 시간을 구현한다.

1

fields_for 도우미에서 "ERB 에코 기호"(=)를 잊어 버렸습니다.

올바른 형태 :

<%= form.fields_for :rooms do |f|%>