Ruby on Rails has

编程入门 行业动态 更新时间:2024-10-06 18:34:37
本文介绍了Ruby on Rails has_many和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Ruby on Rails的新手,并且试图了解抽象类.也许我还记得Java结构...

I'm new to Ruby on Rails and I'm trying to understand abstract class. Maybe I still have in mind Java structure...

我遵循了许多教程,但仍然有一些我需要理解的东西.假设我们要建立一个通讯录.在此通讯录中,我们有人员和公司.

I followed many tutorials and there is still things I'd need to understand. Let's say we want to build a contact book. In this address book, we have people and companies.

class Address < ActiveRecord::Base belongs_to :addressable, :polymorphic => true end class Person < ActiveRecord::Base has_one :address, :as => :addressable end class Company < ActiveRecord::Base has_one :address, :as => :addressable end

目前一切正常.现在,我们有不同的用户,每个用户都有一个通讯簿.

Everything's working fine for now. Now, we have different users, each one has an address book.

class User < ActiveRecord::Base has_one :addressbook end class Addressbook < ActiveRecord::Base has_many ?????? end

无论个人还是公司,我如何列出所有地址?因为我想按字母顺序显示它们...

How do i list all the addresses no matter if they are a person or a company? Because i'd like to display them in alphabetical order...

推荐答案

以下是您的问题的解决方案:

Here is a solution for your problem :

您的Person和Company必须是belongs_to通讯簿. Addressbook has_many :persons和has_many :companies. Addressbook has_many :person_addresses和has_many :company_addresses(使用:through)

Your Person and Company must belongs_to Addressbook. An Addressbook has_many :persons and has_many :companies. An Addressbook has_many :person_addresses and has_many :company_addresses (using :through)

之后,您可以定义一个函数addresses,它是person_addresses和company_addresses的并集.

After, you can define a function addresses, which is the union of person_addresses and company_addresses.

另一种解决方案是声明Person和Company的超类,例如,命名为Addressable.我认为这是一种更漂亮的方式.

An other solution is to declare a super-class for Person and Company, named Addressable for example. I think it's a prettier way.

class Address < ActiveRecord::Base belongs_to :addressable end class Addressable < ActiveRecord::Base has_one :address belongs_to :addressbooks end class Person < Addressable end class Company < Addressable end class User < ActiveRecord::Base has_one :addressbook end class Addressbook < ActiveRecord::Base has_many :addressables has_many :addresses, :through => :addressables end

更多推荐

Ruby on Rails has

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

发布评论

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

>www.elefans.com

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