【发布时间】:2015-10-25 12:35:27
【问题描述】:
如何在我的视图中呈现现有类别的列表?
我的类别表有一个:name 列。
产品视图
= f.select :category_name, Category.all.map{|s| [s.name]}
类别.rb
class Category < ActiveRecord::Base
has_many :categoricals
validates :name, uniqueness: { case_sensitive: false }, presence: true
acts_as_tree order: "name"
end
产品.rb
class Product < ActiveRecord::Base
include ActionView::Helpers
include Categorizable
end
更新:
完整的产品形式
= simple_form_for @product, html: { multipart: true } do |f|
= f.input :title, placeholder: "Product Name", required: false, label: false
= f.input :description, placeholder: "Description", required: false, label: false
= f.select :category_name, Category.all.map{|s| s.name}
= f.input :image, label: false
= f.button :submit, class: "button"
更新#2: 产品控制器
def update
if @product.update(product_params)
redirect_to @product, notice: "Your Product was successfully updated!"
else
render 'edit'
end
end
分类模型
class Categorical < ActiveRecord::Base
belongs_to :category
belongs_to :categorizable, polymorphic: true
validates_presence_of :category, :categorizable
end
分类模块
module Categorizable
extend ActiveSupport::Concern
included do
has_many :categoricals, as: :categorizable
has_many :categories, through: :categoricals
end
def add_to_category(category)
self.categoricals.create(category: category)
end
def remove_from_category(category)
self.categoricals.find_by(category: category).maybe.destroy
end
module ClassMethods
end
end
【问题讨论】:
标签: ruby-on-rails database view