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
我有,在category.rb:'的has_many:products' 和product.rb,我有'belongs_to的:category' 你是說我需要改變那些你是否推薦或者應該沒問題? – Nick
完全沒問題,你在數據庫中是否也有ID?例如。產品表中的category_id? –
是的(我在原始問題中粘貼了產品表) – Nick