2013-08-20 21 views
1

我創建一個非常基本的電子商務應用程序來教自己的軌道上會導致訪問,我已經打了我的第一個障礙:限制:協會在我的Rails應用形式

我創造了一些關聯,以便商家可以爲他們發佈的產品分配類別,但這種方式的效果很好,但是,現在它的工作方式是,當商家創建新產品時,類別表中的所有類別都可供選擇。假設,如果我想限制該列表僅限於該特定商家創建或關聯的類別,我推測來自categories_merchants表,我該如何去做?

我已經展示了相關的表和下方的形式展現我做了什麼,但離開了模特,但是我在他們所有適當的關聯:

產品表:

create_table :products do |t| 
    t.integer :merchant_id 
    t.string :title 
    t.text :body 
    t.date :publish_date 
    t.date :expiry_date 
    t.timestamps 

分類表:

create_table :categories do |t| 
    t.string :name 
    t.timestamps 

Categories_Products表:

create_table :categories_products, :id =>false do |t| 
    t.integer :category_id 
    t.integer :product_id 
end 
add_index :categories_products, [:category_id, :product_id] 

Categories_Merchants表:

create_table :categories_merchants, :id =>false do |t| 
    t.integer :category_id 
    t.integer :merchant_id 
end 
add_index :categories_merchants, [:category_id, :merchant_id] 

新產品形式:提前

<%= simple_form_for(@product) do |f| %> 
    <div class="form-inputs"> 
    <%= f.input :title %> 
    <%= f.input :body %> 
    <%= f.association :categories, :as => :collection_select %> 
    <%= f.input :publish_date %> 
    </div> 
<% end %> 

感謝;)

回答

0

你可以做這樣的事情:

<%= f.association :categories, 
        :as => :collection_select, 
        :collection => Category.includes(:categories_merchants).where("categories_merchants.merchant_id = ?", merchant_id) %>