2015-09-27 79 views
1

我正在挑战自己建立一个小市场,您可以在类别中发布“请求”。为此我有请求模型和类别模型。如何在这些模型之间添加关系,以便该类别知道它属于请求,反之亦然?我已经做了:Ruby on Rails:两种模式之间的关系

category.rb

has_and_belongs_to_many :requests 

request.rb

has_one :category 

现在我的表格里面的部分我有这样的代码:

<%= f.select :category, Category.all, :prompt => "Kategorie", class: "form-control" %> 

的奇怪的是:category不存在,因为列应该是:name。在我seeds.rb我插入以下,其中后运行良好rake db:seed

Category.create(name: 'PHP') 

Category.create(name: 'Ruby') 

Category.create(name: 'HTML') 

Category.create(name: 'ASP') 

Category.create(name: 'C#') 

Category.create(name: 'C++') 

但随着:category上面的代码显示了这一点:

有从种子文件中的所有6个类别,而不是类别的实际名称(如“PHP”)。如果我在这个代码采取:name,而不是:category

<%= f.select :category, Category.all, :prompt => "Kategorie", class: "form-control" %> 

我得到一个

undefined method `name' for #<Request:0x007ff504266b40> 

我的类别表:

Category(id: integer, name: string, description: text, created_at: datetime, updated_at: datetime) 

我如何可以调用类的具体请求,何时保存? @Category.request

我真的很困惑(对不起,我从8月下旬才学习Rails)。

很多感谢提前!

回答

1

如果我理解正确的话,作为一个请求属于一个类别,一类可以有多个请求协会应设立这样的:

class Request < ActiveRecord::Base 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    has_many :requests 
end 

这样在申请表中的项目将有外键category_id到该类别。

您还可以阅读了很多关于协会基本在Active Record Associations Guide

我怎么能要求一个特定的请求的范畴,当它保存? @ Category.request?

要获得类别,你必须从这样的例子请求启动specifc要求:

@request = Request.first 
@reqest.category 

在你的表格你可能接下来要使用category_id,如果你想使用select标签是这样的:

<%= f.select :category_id, Category.all.map { |c| [c.name, c.id] }, :prompt => "Kategorie", class: "form-control" %> 

该地图将确保它将使用标签的名称和您选择的值的id。

为了使关联和其他东西的生成表格更容易,您还可以查看宝石simple_form。那么你所要使用的是:

<%= f.association :category %> 
+0

非常感谢! – CottonEyeJoe