2017-02-13 2 views
0

내 레일 5 앱에 새 제품 (새 제품 게시)을 만들 때 전자 제품, 주택 개선 등의 드롭 다운 메뉴를 통해 카테고리를 선택합니다. 제품을 만든 후 다시 편집하면 카테고리를 다시 선택하면 더 이상 카테고리가 없습니다. 편집 할 때 범주가 기억되거나 미리 채워지도록하려면 어떻게해야합니까? 아마 멍청한 녀석을 위해 쉽게 ... 고마워! 게시물/제품을 편집 할 때 범주를 기억하려면 어떻게해야합니까? (다시 선택해야합니까?)

양식의 범주 입력 필드 :

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 
: 내가 게시해야 다른 모르는

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


, 그래서 여기에 카테고리 컨트롤러 코드입니다

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" 

답변

0

솔직히 말해서. 일반적인 스캐 폴드 컨트롤러 동작을 사용할 수 있습니다. 상품 항목에 category_id에 대한 DB 항목이 있고 모델에 동일한 연관성이 있어야합니다. 예 :

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

당신의 products_controller.rb에서보다 것은 paramscategory_id를 추가하고 성공적으로 그것이 당신의 편집뿐만 아니라 쇼보기에 표시됩니다 저장 될 때. 더 자세한 정보는 R-O-R 협회의 DOCS를 확인하십시오. 제품에 여러 범주가 있어야하는 경우 다른 유형의 연결을 선택할 수 있습니다. 여기에 링크 : http://guides.rubyonrails.org/association_basics.html

+0

내가 가지고 category.rb에'has_many는 : 을 products' 및 product.rb에, 나는 belongs_to'이 : category' 당신은 내가 무엇을 사람들을 변경해야하는 건가요 그 것이 좋았습니까? – Nick

+0

완전히 괜찮습니다. DB에 ID가 있습니까? e, g. 제품 테이블의 category_id? –

+0

예 (원래 질문에 제품 표를 붙여 넣었습니다) – Nick

관련 문제