Ruby on Rails的:创建一个belongs_to的关联模型项 [英] Ruby on rails: Creating a model entry with a belongs_to association
问题描述
我想加在我的数据库中的新条目,有一个belongs_to的关系的典范。我有2个型号,乔布斯和客户端。
这是很容易找到如何建立这两个(使用的has_many和belongs_to的)之间的关联的教程,但我似乎无法找到的地方实际使用关联的任何实例。
在我的code,我试图创建第一个客户端一个新的工作。该工作模式有CLIENT_ID一个属性,我知道我可以很可能只是手工填写属性,但必须有一些红宝石约定很容易做到这一点。
Job.create(:CLIENT_ID => 1:主题=>中测试:描述=>中这是一个测试)
我可以很容易地把在我的code,但我觉得Ruby有一个更好的方式来做到这一点。这里是我的模型设置方式
类招聘< ActiveRecord的::基地
attr_accessible:actual_time,:assigned_at,:CLIENT_ID,:completed_at,:estimated_time,:位置,:responded_at,:runner_id,:状态:主题,:说明
belongs_to的:客户端
结束一流的客户<用户
的has_many:工作
结束类User< ActiveRecord的::基地
attr_accessible:姓名,:细胞:电子邮件:preF结束
就叫创建
在工作
集合客户端的
C = Client.find(1)
c.jobs.create(:主题=>中测试:描述=>中这是一个测试)
I am trying to add a new entry in my database for a model that has a belongs_to relationship. I have 2 models, Jobs and Clients.
It was easy enough to find tutorial on how to set up the association between these two (using has_many and belongs_to), but I can't seem to find any examples where the association is actually used.
In my code, I am trying to create a new job for the first client. The jobs model has an attribute for client_id, and I know I can probably just manually fill the attribute, but there has to be some ruby convention to easily accomplish this.
Job.create(:client_id => 1, :subject => "Test", :description => "This is a test")
I can easily put that in my code, but I feel like ruby has a better way to do this. Here is the way my models are setup
class Job < ActiveRecord::Base
attr_accessible :actual_time, :assigned_at, :client_id, :completed_at, :estimated_time, :location, :responded_at, :runner_id, :status, :subject, :description
belongs_to :client
end
class Client < User
has_many :jobs
end
class User < ActiveRecord::Base
attr_accessible :name, :cell, :email, :pref
end
Just call create
on the jobs
collection of the client:
c = Client.find(1)
c.jobs.create(:subject => "Test", :description => "This is a test")
这篇关于Ruby on Rails的:创建一个belongs_to的关联模型项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!