如何在 Rails 中创建类别 [英] How to create Categories in Rails

查看:23
本文介绍了如何在 Rails 中创建类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将类别添加到我的 Rails 应用程序,但不太知道如何执行此操作.

i'm trying to Add Categories to my Rails app, but don't quite know how to do this.

我有很多 Pin 图(图片)并且希望用户能够在这些 Pin 图上分配一个类别.ASSIGN 不会创建、编辑或删除类别,只需为其 Pin 图选择一个类别即可.这意味着,当用户上传 Pin 图时,他可以从下拉列表中选择一个类别.

I have many Pins(Images) and want the user to be able to assign a category on those Pins. ASSIGN not create, edit, or delete a Category, just selecting one for their Pin. Meaning that, When a user uploads a pin, he can choose from a dropdown list a Category.

然后,另一个用户可以从菜单中选择一个类别,并且只会列出该类别中的 Pin 图.

Then, another user can choose from the Menu a Category, and ONLY the Pins in this Category will be listed.

我该怎么做?从哪里开始?

How do i do this? Where to start ?

谢谢

推荐答案

首先如果您不想在应用程序中管理类别,那么您可以简单地在您的表中添加一个类别字段并在您的应用程序中选择类别:

First If you don't want to manage categories in your application, then you can simply add a category field in your table and category select in your application :

<%= f.select :category, [ 'Box', 'Cover', 'Poster' ], :prompt => 'Select One' %>

第二,如果你想在你的应用程序中管理类别,那么你必须为它维护一个单独的模型和表.因此,您可以从生成模型开始:

Second, If you want to manage categories in your application, than you have to maintain a separate model and table for it. So you can start with generating your model:

rails g model category

它将在您的应用程序目录中添加模型和迁移.向您的迁移添加内容:

it will add model and migration in your application directory. Add stuff to your migration:

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name
      t.text :description
      ## you can add more stuff as per your requirements 
      t.timestamps
    end
  end
end

在类别中定义关联 &Pin 模型为此添加验证:-

Define associations in category & Pin model add validation for this :-

In Category Model:
  has_many :pins

In Pin Model :
  belongs_to :category
  validates :category, presence: true

通过类别控制器和表单创建一些类别(我认为不需要,我需要告诉你那些东西,你可以自己做)

Create some categories by categories controller and form (I don't think, I need to tell you that stuff, you are able to do it yourself)

在您的 pin 上传表单中添加此选择 :-

In your pin uploading form add this select :-

<%= f.select :category, Category.all, :prompt => "Select One" %>

希望,它会有所帮助.

这篇关于如何在 Rails 中创建类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆