Rails:在元素和第二级嵌套元素之间创建关联

发布于 2024-11-02 10:37:31 字数 623 浏览 2 评论 0原文

以下系统用于管理联系人。 每个联系人都属于一个组织,每个组织都有许多位置。联系人还与上级组织的一个位置相关。 组织模型看起来像这样,

has_many :contacts
has_many :locations
accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a["name"].blank? }

我希望它接受位置的嵌套属性,因为当用户添加组织时,他还可以动态为其添加位置。

联系人模型看起来像这样

  has_one :location
  belongs_to  :organisation
  accepts_nested_attributes_for :organisation

同一个故事,当添加联系人时,我希望用户能够动态添加组织,但组织需要有一个位置,因此视图中还存在第二层嵌套为组织创建位置。 它工作正常,它添加了联系人,它添加了组织和位置,它创建了位置和组织之间的关联,但发生的情况是我在联系人中有一个字段“location_id”,我想在其中包含 id动态为组织添加的位置。有谁知道通过模型来完成此操作的干净方法,或者我是否必须通过在控制器中进行一些调整来解决它?

The following system is for managing contacts.
Each contact belongs to an organisation, and each organisation has many locations. A contact is also related to one location from the parent organisation.
The organisation model looks like this

has_many :contacts
has_many :locations
accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a["name"].blank? }

I want it to accept nested attributes for locations because when a user adds an organisation he can also add a location for it on the fly.

The contact model looks like this

  has_one :location
  belongs_to  :organisation
  accepts_nested_attributes_for :organisation

Same story, when a contact is added I want the user to be able to add the organisation on the fly, but the organisation needs to have a location, so a second level of nesting exists in the view to also create the location for the organsiation.
It works fine, it adds the contact, it adds the organisation and the location, it creates the association between the location and the organisation but what happens is that I have a field "location_id" in contact and I want to have in that the id of the location added for the organisation on the fly. Does anyone know a clean way to do it through the model or do I have to workaround it with some tweaks in the controllers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅哥哥的热头脑 2024-11-09 10:37:31

如果您使用@location = @contact.build_location,它应该创建您当前缺少的ID,即使@contact的ID在构建时不存在。

If you use @location = @contact.build_location it should create the ID that you are currently missing, even though the id of @contact does not exist at the time of the build.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文