Has_many :通过关联
我使用 has_many :through
与三个模型建立了关系:
class Curriculum class < ActiveRecord::Base
has_many :interests
has_many :vacancies,: through => :interests
end
class Vacancy class < ActiveRecord::Base
has_many :interests
has_many :resumes,: through => :interests
end
class Interest < ActiveRecord:: Base
belongs_to :vacancy
belongs_to :curriculum
end
为了创建课程和职位空缺,我通过管理创建它们,我需要知道如何创建对空缺 ID 的兴趣,以及如何将其登录到系统上,我必须获取它的 ID 并在创建新的银行利息时建立关系。我想知道如何对其进行编程来做到这一点,我想知道控制器将如何获得创建操作,以及有什么更好的方法来做到这一点。
I made a relationship with the three models using has_many :through
:
class Curriculum class < ActiveRecord::Base
has_many :interests
has_many :vacancies,: through => :interests
end
class Vacancy class < ActiveRecord::Base
has_many :interests
has_many :resumes,: through => :interests
end
class Interest < ActiveRecord:: Base
belongs_to :vacancy
belongs_to :curriculum
end
And to create curriculum and vacancy, I create them by administrative, i need to know how can i create the interest to the id of the vacancy, and how it will be logged on the system I have to get the id of it and make the relationship in creating a new bank interest. I wonder how I can program it to do so, and I wonder how the controller will get the create action, and what better way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,尝试阅读整个“Rails 关联指南”,特别是关于
has_many :through
的部分。然后检查您的架构,如果您的数据库已迁移,并且表interests
包含curriculums
和vacancies
的必要外键,称为curriculum_id< /code> 和
vacancy_id
。如果一切就绪,以下代码将创建两个对象之间的关系:
最后两行在
@curr
和@vac
之间创建兴趣并将其存储在数据库。因此,您不应该使用 ID 并直接处理它们,而应该使用对象。现在的第二部分是提供一个 UI,以允许定义(和删除)课程和职位空缺之间的兴趣。这里的基本流程是:
请参阅(较旧的)播客 Railscast #52 如何在类似的上下文中执行此操作。或者查看 has_many :through 和复选框的示例。
另一种方法是使用 JQuery 自动完成,并逐一添加兴趣。请参阅不错的播客 Railscast #258,它使用 JQuery Tokeninput 来实现这一点。
First, try to read the whole "Guide to Rails on Associations", especially the part about
has_many :through
. Then check your schema if your db is migrated and contains for the tableinterests
the necessary foreign keys tocurriculums
andvacancies
calledcurriculum_id
andvacancy_id
.If that is all in place, the following code will create the relationship between two objects:
The last two lines creates an interest between
@curr
and@vac
and store that on the database. So you should not use IDs and handle them directly, but work with objects instead.The second part now is to provide a UI to allow the definition (and removal) of interests between curricula and vacancies. The base flow here is:
See the (older) podcast Railscast #52 how to do that in a similar context. Or see the example for has_many :through with checkboxes.
An alternative way would be to use JQuery autocomplete, and add so interests one-by-one. See the nice podcast Railscast #258 which uses JQuery Tokeninput for that.
我认为这就是您要寻找的:
HABTM 复选框
这是使用 < strong>拥有并属于许多关联。
I think this is what your looking for:
HABTM Checkboxes
That's the best way to use an Has and Belongs to many association.