2017-02-13 109 views
0

當我在我的Rails 5應用程序中創建新列表(新產品發佈)時,我通過下拉菜單選擇一個類別,例如電子產品,家居裝修等。如果創建項目後返回並編輯它,我有再次選擇一個類別,否則它將不再擁有一個類別。當我去編輯時,如何告訴該類別被記住或預先填充?可能很容易對非noob ...謝謝!編輯帖子/產品時,如何獲取它以記住類別(我不必重新選擇它)?

這是窗體上的類別輸入字段:

<div class="field"> 
<%= f.label :category %> 
<%= select_tag(:category_id, options_for_select(Category.all.map{|c| [ c.name, c.id]}), :prompt => "Select one!") %> 


我不知道我應該張貼別的什麼,所以這裏的類控制器代碼:

class CategoriesController < ApplicationController 
before_action :set_category, only: [:show, :edit, :update, :destroy] 

def index 
@categories = Category.all 
end 

def show 
end 

def new 
@category = Category.new 
end 

def edit 
end 

def create 
@category = Category.new(category_params) 

respond_to do |format| 
if @category.save 
format.html { redirect_to @category, notice: 'Category was  successfully created.' }  
else 
    format.html { render :new } 
    end 
end 
end 

def update 
respond_to do |format| 
    if @category.update(category_params) 
    format.html { redirect_to @category, notice: 'Category was successfully updated.' } 
    else 
    format.html { render :edit } 
    end 
end 
end 

def destroy 
@category.destroy 
respond_to do |format| 
    format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' } 
end 
end 

private 
@category = Category.find(params[:id]) 
end 

def category_params 
    params.require(:category).permit(:name, :desc) 
end 
end 

DB中的產品表:

create_table "products", force: :cascade do |t| 
t.string "name" 
t.text  "brief" 
t.text  "description" 
t.string "buylink" 
t.string "verdict" 
t.string "category_id" 
t.datetime "created_at", null: false 
t.datetime "updated_at", null: false 
t.string "image" 
t.string "youtube" 
t.integer "user_id" 
t.string "goodverdict" 

end

回答

0

說實話。您可以使用通常的腳手架控制器操作。您需要確保您的產品項目具有category_id的數據庫列,並且在您的模型中具有等效關聯,例如,

product.rb 
    has_one :category 
category.rb 
    belongs_to :product 

比你products_controller.rb添加category_idparams,當它被成功救了它會在你的編輯,以及在你的節目的意見顯示。有關更詳細的信息,請查看關於R-O-R關聯的DOCS。如果您的產品應該有多個類別,您可以選擇不同類型的關聯。這裏的鏈接: http://guides.rubyonrails.org/association_basics.html

+0

我有,在category.rb:'的has_many:products' 和product.rb,我有'belongs_to的:category' 你是說我需要改變那些你是否推薦或者應該沒問題? – Nick

+0

完全沒問題,你在數據庫中是否也有ID?例如。產品表中的category_id? –

+0

是的(我在原始問題中粘貼了產品表) – Nick

相關問題