Ruby on Rails:将一个模型的2个引用添加到另一个模型 [英] Ruby on rails: Adding 2 references of a single model to another model

查看:97
本文介绍了Ruby on Rails:将一个模型的2个引用添加到另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Rails 4.0上的红宝石中实现我的情况的正确方法。

I'd like to know a proper way to implement my situation here in ruby on rails 4.0.

让我们说我有2个名为 House Order

Lets say I have 2 models named House and Order.

我的订单表应具有两列 from to 都引用房屋模型。

My Order table should have two columns from and to both referencing a house model.

在这种情况下,这两个模型之间的关系应该是什么?
注意:我不需要从房屋模型中引用任何订单模型。

What should my relations between these two models be in this case? Note: I do not require any reference to order model from house model.

我想在其中添加类似的东西我的订单表

I would like to have something like this in my Order table

t.references :house, as:from (this should create a column named from and should be of type integer, index of house table
t.references :house, as:to (this should create a column named to and should be of type integer, index of house table

我希望在订单模型中使用这种类型的关系,因为我想以订单的形式获取房屋领域,例如

I would like this type of relation in order model because I want to take fields of houses in my order form something like

<%= form_for @order do |f| %>
  ... # order fields
  <%= f.fields_for :house(from) do |i| %>
    ... # your house forms
  <% end %>
  <%= f.fields_for :house(to) do |i| %>
    ... # your house forms
  <% end %>
  ...
<% end %>

有没有特定的方法可以

P.S:我已经在这里阅读过这篇文章,但是我认为它不能完全解决我的问题。
向现有Rails模型添加模型引用

P.S : I have already read this post here but I think it does not exactly solve my problem. Adding a Model Reference to existing Rails model

推荐答案

在创建订单迁移文件中:

In create orders migration file:

create_table :orders do |t|
  ..
  t.integer :from_house_id
  t.integer :to_house_id
  ..
end

在您的应用/模型/订单中。rb:

In your app/models/order.rb:

belongs_to :from_house, class_name: 'House'
belongs_to :to_house, class_name: 'House'

accepts_nested_attributes_for :from_house, :to_house

在您看来:

<%= form_for @order do |f| %>
  ... # order fields
  <%= f.fields_for :from_house do |i| %>
    ... # your from house forms
  <% end %>
  <%= f.fields_for :to_house do |i| %>
    ... # your to house forms
  <% end %>
  ...
<% end %>

享受!

这篇关于Ruby on Rails:将一个模型的2个引用添加到另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆