문제

나는 두 개체 사이에 다수의 연관성을 설정하려고 노력하고 있습니다. 여러 튜토리얼을 살펴보고 모델을 올바르게 설정할 수있었습니다. 내 문제는 올바른 경로를 설정하는 데 어려움이 있다는 것입니다. 전체 관계를 볼 수 있습니다. 특정 범주에서 제품을 표시하는 것과 같은 것 (/카테고리/1/제품/)

이것이 모델을 생성 한 방법입니다.

script/generate scaffold category name:string
script/generate scaffold product name:string
script/generate scaffold categorization category_id:integer product_id:integer

스키마는 다음과 같습니다.

ActiveRecord::Schema.define(:version => 20100205210519) do

  create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorizations", :force => true do |t|
    t.integer  "category_id"
    t.integer  "product_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "products", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

다음은 3 가지 모델 객체입니다.

class Category < ActiveRecord::Base
    has_many :categorizations
    has_many :products, :through => :categorizations
end

class Product < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, :through => :categorizations
end

class Categorization < ActiveRecord::Base
    belongs_to :product
    belongs_to :category
end

콘솔을 통해 제품을 카테고리에 추가 할 수 있기 때문에 매우 간단하고 모든 것이 잘 작동하는 것 같습니다.

@category.categorizations << Categorization.new(:product_id => 1)

나는 loures.rb 파일을 업데이트해야한다고 확신하지만 실제로 올바른 방법을 모른다. 이것이 내가 경로 파일에 넣은 것입니다.

map.resources :categories, :has_many => :products

카테고리에서 제품을 보려고 할 때 "/category/7/products/"모든 제품 만 나열됩니다! 이것은 내 경로가 올바르게 설정되었으며 제품 컨트롤러에 사용자 정의 조치를 작성하면 (색인을 표시하는 대신)? 내가 여기서 무엇을 잘못하고 있습니까 ... 내가 가까이 또는 벗어나?!?

감사

도움이 되었습니까?

해결책

경로의 데이터를 사용하여 제품 목록을 필터링하지 않을 것입니다.

Product_Controller의 색인 메소드에서 다음과 같은 작업을 수행해야합니다.

Category.find(params[:category_id]).products

다른 팁

당신이하고 싶은 것은 중첩 된 자원을 사용하는 것입니다. 일반 형식은 다음과 같습니다.

map.resources :users do |users|
  users.resources :posts
end

그것에 대해 자세히 알아보십시오 여기.

제안 된 바와 같이 이 질문, 찾기 쿼리에 요청 매개 변수 : category_id를 추가 할 수 있습니다.

항상 출력을보십시오 레이크 노선.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top