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

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

问题描述

我尝试添加类别到我的Rails应用程序,但不知道如何做这个。



我有很多Pins用户能够在这些引脚上分配类别。
ASSIGN 不能创建,修改或删除类别,只需为其定位选择一个。
意思是,当用户上传一个pin,他可以从下拉列表中选择一个类别。



然后,另一个用户可以从菜单中选择一个类别,并且只列出此类别中的引脚。



我该如何做?从哪里开始?



谢谢

解决方案

不想在应用程式中管理类别,只要在应用程式中的表格和类别选项中新增类别栏位:

 <%= f.select:category,['Box','Cover','Poster'],:prompt => '选择一个'%> 

其次,如果要在应用程序中管理类别,表为它。所以你可以从生成你的模型开始:

  rails g模型类别
pre>

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

  class CreateCategories< ActiveRecord :: Migration 
def change
create_table:categories do | t |
t.string:name
t.text:description
##你可以根据你的要求添加更多的东西
t.timestamps
end
end
end

定义类别& Pin模型添加验证为: -

 在类别模型:
has_many:pins

In Pin型号:
belongs_to:category
validates:category,presence:true

按类别控制器和表单创建一些类别(我不认为,我需要告诉你的东西,你能够自己做)



在你的pin uploading form add this select: -

 <%= f.select:category,Category.all,:prompt => ; 选择一个%> 

希望,这将有所帮助。


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

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.

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 ?

Thank you

解决方案

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

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)

In your pin uploading form add this select :-

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

Hope, It will help.

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

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