4

레일에 다중 테이블 상속을 사용하여 개체의 중첩 된 양식을 작성하려면 어떻게해야합니까? 다중 테이블 상속 기능을 가진 다른 모델 집합과 has_many 관계가있는 모델을 사용하여 개체를 만드는 중첩 된 폼을 만들려고합니다. 중첩 된 양식에는 formtasticcocoon을 사용하고 복수 테이블 상속을 구현하려면 act_as_relation 보석을 사용하고 있습니다.다중 테이블 상속을 사용하는 중첩 된 양식

나는 다음과 같은 모델이이 예를 들어

class Product < ActiveRecord::Base 
acts_as_superclass 
belongs_to :store 
end 

class Book < ActiveRecord::Base 
    acts_as :product, :as => :producible 
end 

class Pen < ActiveRecord::Base 
    acts_as :product, :as => :producible acts_as :product, :as => :producible 
end 

class Store < ActiveRecord::Base 
    has_many :products 
    accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank 
end' 

을,이 책은 다른 제품에 비해 한 유일한 고유 한 속성 것을 저자 필드입니다. 실제로는 책에 대한 고유 한 속성이 많아서 더 일반적인 단일 테이블 상속에 비해 다중 테이블 상속을 선택했습니다.

제품이있는 새 저장소를 만들 수있는 중첩 된 양식을 만들려고합니다. 여기 내 양식이다 :

<%= semantic_form_for @store do |f| %> 
    <%= f.inputs do %> 
    <%= f.input :name %> 

    <h3>Books/h3> 
    <div id='books'> 
    <%= f.semantic_fields_for :books do |book| %> 
     <%= render 'book_fields', :f => book %> 
    <% end %> 
      <div class='links'> 
     <%= link_to_add_association 'add book', f, :books %> 
     </div> 

    <% end %> 
<%= f.actions :submit %> 
<% end %> 

그리고 book_fields 부분 : act_as_relation의 GitHub의 페이지에서 문제를 읽고 바탕으로

undefined method `new_record?' for nil:NilClass 

, 나에 대한 생각 :

<div class='nested-fields'> 
    <%= f.inputs do %> 
    <%= f.input :author %> 
    <%= link_to_remove_association "remove book", f %> 
    <% end %> 
</div> 

나는이 오류 상점과 책의 관계를보다 명확하게 만듭니다.

class Product < ActiveRecord::Base 
acts_as_superclass 
belongs_to :store 
has_one :book 
accepts_nested_attributes_for :book, :allow_destroy => true, :reject_if => :all_blank 
end 

class Book < ActiveRecord::Base 
    belongs_to :store 
    acts_as :product, :as => :producible 
end 

class Store < ActiveRecord::Base 
     has_many :products 
     has_many :books, :through => :products 
     accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank 
     accepts_nested_attributes_for :books, :allow_destroy => true, :reject_if => :all_blank 
    end 

이제 침묵 오류가 발생합니다. 양식을 사용하여 새 상점을 만들 수 있으며 고치기를 사용하면 새 서평 필드를 추가 할 수 있지만 제출하면 저장소가 생성되지만 하위 책은 생성되지 않습니다. `/ books/new '경로를 살펴볼 때 문제가없는 새로운 책 레코드 (제품과 책 테이블)를 만들 수 있습니다.

이 문제를 해결할 수있는 방법이 있습니까? 나머지 코드는 here입니다.

+0

당신이 볼 수있는 PARAMS 해시를 확인해 봤어을 아동 도서 속성 경우 제대로 포함 되었습니까? –

답변

2

어쩌면 당신은 할 수 :

  • 당신의 stores_controller#new 행동에 수동으로

    @store.books.build

    당신에
  • 스토어 수동의 관계 stores_controller#create 행동

    @store.books ... (정말이 책의 관계를 구축 그것을 달성하는 방법에 대한 자신감)

Google에 게시하십시오.

+0

컨트롤러에서 수동으로 더 많은 작업을 수행하려는 아이디어를 바탕으로 이제 create_assocation 메서드를 사용하려고 시도하지만 메서드가 메타 프로그래밍을 통해 자동으로 연결되지 않는 것처럼 보입니다. – sutee

+1

나는 그것을 결국 알아 냈다. 일단 내가 그것을 정리하고 그것을 얻는 데 필요한 최소한의 변경 횟수를 결정하면 나는 해결책을 게시 할 것이다. 당신의 대답이 최종 해결책에 가장 가깝기 때문에 현상금을 수여합니다. 감사합니다! – sutee

+0

귀하의 의견 ... 바쁜 주에 응답 할 수 없어서 죄송합니다. 질문을 답변으로 표시되도록 솔루션을 게시하고 동의하십시오. 다행히 도울 수있어. – rlecaro2

1

나만의 양식 개체를 만드는 것이 좋습니다.이것은 RailsCast 프로 비디오이지만, 여기에 ASCIIcast의 예제의 일부입니다 :

def new 
    @signup_form = SignupForm.new(current_user) 
end 

단지 원래의 컨트롤러 코드에서 당신이하는 것처럼, 다른 객체에 대한 관계를 포함 할 수 있습니다이 가입 양식 :

class SignupForm 
    # Rails 4: include ActiveModel::Model 
    extend ActiveModel::Naming 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 

    validates_presence_of :username 
    validates_uniqueness_of :username 
    validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ 
    validates_length_of :password, minimum: 6 

    def persisted? 
    false 
    end 

    def subscribed 
    subscribed_at 
    end 

    def subscribed=(checkbox) 
    subscribed_at = Time.zone.now if checkbox == "1" 
    end 

    def generate_token 
    begin 
     self.token = SecureRandom.hex 
    end while User.exists?(token: token) 
    end 
end 

다음은 RailsCast에 대한 링크입니다. 직업적 회원을 얻는 것이 시간을 할애 할만한 가치가 있을지 모릅니다.

RailsCast : 나는 당신이 과정을 완료 할 때 '상품'얻을 수 www.codeschool.com을 통해 회원과 운이 받고있다 http://railscasts.com/episodes/416-form-objects

관련 문제