Ruby on Rails的:创建一个belongs

编程入门 行业动态 更新时间:2024-10-28 02:25:58
本文介绍了Ruby on Rails的:创建一个belongs_to的关联模型项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想加在我的数据库中的新条目,有一个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

本文发布于:2023-10-28 22:37:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:创建一个   Ruby   Rails   belongs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!