2013-09-26 2 views
1

나는 작품 목록을 표시해야하는 앱을 제작 중입니다. 각 작품은 Work 모델로 표시되며 WorkPicture 모델로 대표되는 여러 그림을 포함 할 수 있습니다. 나는이 모델의 인스턴스에 연결된 적어도 하나 개의 그림이 있는지 확인하기 위해 라인 validates :pictures, length: { minimum: 1, message: "are not enough." }을 사용하고모델의 유효성을 검사하지 않고 has_many 관계에 금액 제약 조건 추가

class Work < ActiveRecord::Base 
    belongs_to :category 

    has_many :pictures, class_name: "WorkPicture", dependent: :destroy 
    accepts_nested_attributes_for :pictures, allow_destroy: true 

    # Ensures that we have at least 1 picture 
    validates :pictures, length: { minimum: 1, message: "are not enough." } 

    validates :name, presence: true 
    validates :description, presence: true 
    validates :category_id, presence: true 

end 

work.rb. 여기


는 그림 (가 첨부 된 사진의 paperclip 보석 사용)에 대한 모델 :

work_picture.rb을

class WorkPicture < ActiveRecord::Base 
    belongs_to :work 

    CONVERT_OPTIONS = "-gravity north" 
    has_attached_file :picture, styles:   { big: ["945x584#", :png], thumb: ["360x222#", :png] }, 
           convert_options: { big: CONVERT_OPTIONS, thumb: CONVERT_OPTIONS } 
    validates_attachment :picture, presence:  true, 
           content_type: { content_type: /image/ } 
end 

나는 문제가 테스트를 데 이 두 모델 간의 관계. 나는 단순히 그것을 미리 정의 된 그림을 추가,

factories.rb :work_picture 공장에서

include ActionDispatch::TestProcess 

FactoryGirl.define do  
    factory :work do 
    sequence(:name) { |n| "Project #{n}" } 
    description  "A description" 
    category 

    after :build do |work, evaluator| 
     create(:work_picture, work: work) # Creating a picture for this work 
    end 
    end 

    factory :category do 
    sequence(:name) { |n| "Category #{n}" } 
    end 

    factory :work_picture do 
    picture { fixture_file_upload Rails.root.join("spec/fixtures/files/work.png"), "image/png" } 
    work 

    after :create do |work_picture, evaluator| 
     evaluator.picture.close 
    end 
    end 
end 

: 여기에 내가 factory_girl 보석을 사용하여 설정하기 위해 노력하고있어 방법이다.

:work 공장에서, 나는 그것이 방금 생성되었을 때 작업에 사진을 추가하려고하지만,이 작업을 제대로을 연관하는 work_picture가 유효한 ID가 필요하기 때문이 수행 될 수 없으며, 그것은 내가 만들고있는 작품이 저장되지 않았기 때문에 가능하지 않습니다. 따라서 ID가 없습니다.

사진을 저장할 때 (사진을 저장할 때) 사진을 연결하는 방법이 필요합니다. 작업이 저장되면 사진의 수를 확인하고 어떤 사진에도 연결되지 않았기 때문입니다. 사진이 아직 유효하지 않으며 사진에 대한 ID가 여전히 없습니다.

생각해 보면 사진에 ID가있는 작업이 필요하지만 작업에 그림이 필요하기 때문에 ID를 할당 할 수 있으므로 약간의 역설적 인 것으로 나타납니다. 두 조건 중 어느 것도 진실이 이루어지기 전에 다른 조건에 의존하지 않습니다.

다음은 Work 모델에 대한 내 사양입니다 :

work_spec.rb

require 'spec_helper' 

describe Work do 
    let!(:work) { build(:work) } 
    subject { work } 

    it { should respond_to :name } 
    it { should respond_to :description } 
    it { should respond_to :category } 
    it { should respond_to :category_id } 

    it { should respond_to :pictures } 

    it { should be_valid } # Fails, because we have no picture 

    # ... Unrelated tests omitted 

    # This test is here to check if the factory_girl setup is working 
    describe "picture count" do 
    it "should be 1" do 
     expect(work.pictures.count).to eq 1 # Fails, because we are unable to add the picture 
    end 
    end 
end 

내 질문

나는 그래서이 문제를 해결하려면 어떻게해야 하나 이상에 대한 요구 사항 모델에있는 사진이 제자리에 남아 있지만, 동시에 나는 insta를 생성 (저장) 할 수 있습니다. 그것이 사진과 관련되기 전에 그것의 nce?

답변

0

work_picture의 첫 번째 줄을 변경해보십시오.rb ~

belongs_to :work, inverse_of: :pictures 
+0

감사합니다. 나는 그것이 내일 아침에 첫 번째로 작동하는지 보겠습니다. –

+0

죄송합니다. 방금 시도했지만 작동하지 않았습니다. 나는 여전히 같은 문제가있다. –

0

해결책을 찾은 것 같습니다. 콘솔에서 장난을 치고 난 후에 나는 work.pictures.build을 사용하여 저장하지 않고도 내 모델에 바인드 된 더미 work_picture을 만들 수 있음을 발견했습니다. 이렇게하면 그림을 그림과 연결하고 저장하기 전에 유효성 검사를 전달할 수 있습니다. 일단 저장되면 모든 것이 정상적으로 작동합니다.

factories.rb

include ActionDispatch::TestProcess 

FactoryGirl.define do 
    # ... 

    factory :work do 
    sequence(:name) { |n| "Project #{n}" } 
    description  "A cool description" 
    category 

    after :build do |work| 
     work_picture = work.pictures.build # Builds a dummy picture 
     work_picture.update_attributes(attributes_for(:work_picture)) # Loads the picture file 
    end 
    end 

    # ... 
end 

나는 또한 그 모든 것을 확인하기 위해 내 시험을 쥐게 한 바로 작품 :

여기에 내가 변경 한 내용은

work_spec.rb

require 'spec_helper' 

describe Work do 

    # ... 

    # Checks if the factory_girl setup is working 
    describe "picture length" do 
    it "should be 1" do 
     expect(work.pictures.length).to eq 1 
    end 
    end 

    describe "picture count after save" do 
    before { work.save } 

    it "should be 1" do 
     expect(work.pictures.count).to eq 1 
    end 
    end 
end