【问题标题】:Ruby on rails: Adding 2 references of a single model to another modelRuby on rails:将单个模型的 2 个引用添加到另一个模型
【发布时间】:2014-09-01 19:26:25
【问题描述】:

我想知道在 ruby​​ on rails 4.0 中实现我的情况的正确方法。

假设我有 2 个模型,分别名为 House 和 Order。

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

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

我想在我的 Order 表中有这样的东西

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

我想在订单模型中使用这种类型的关系,因为我想在我的订单中获取房屋字段,例如

<%= 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 %>

在 Rails 中有什么具体的方法吗?

P.S : 我已经在这里阅读了这篇文章,但我认为它并不能完全解决我的问题。 Adding a Model Reference to existing Rails model

【问题讨论】:

    标签: ruby-on-rails forms database-design rails-models


    【解决方案1】:

    在创建订单迁移文件中:

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

    在您的 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 %>
    

    享受吧!

    【讨论】:

    • 非常感谢。这正是我一直在寻找的。我认为它的 accepts_nested_attributes_for :from_house, :to_house, 在 order 模型中。我已经做出了改变。之后我尝试实现上述内容,但表格根本没有出现。我的服务器没有显示任何错误。字段中的所有字段均未显示。不知道是什么原因?
    • 我的错,有错字!对不起。您需要在控制器中输入@order.build_from_house 和@order.build_to_house,它就会出现!如果答案有帮助,请接受它,因为该答案将来也可能对其他人有所帮助。 :)
    • 嘿,Surya,我还有一个小问题,你能帮我解决一下吗?在上述场景中,我还有一个 User 模型。我有以下关系,Order belongs_to :user 和 User has_many :orders。相似地。 house belongs_to :user 和 user has_many :houses。我还在为 :user 订购 f.fields。除了内部模型中的 user_id 为 NULL 之外,一切都得到了很好的更新。我希望那是刚刚在这里创建的用户。我怎样才能做到这一点?
    • 我很乐意提供帮助。请创建另一个问题,在 cmets 中很难跟进问题。
    • 谢谢。会这样做。
    【解决方案2】:

    添加这个答案以防 Surya 的代码不起作用 - 我习惯于指定 foreign_key:

    class Order < ActiveRecord::Base
      belongs_to :from_house, :class_name => "House", :foreign_key => "from_id"
      belongs_to :to_house, :class_name => "House", :foreign_key => "to_id"
    end
    

    只需确保您在 Order 上有两个属性 - 一个是 from_id,另一个是 to_id。从现在开始您可以拨打order.from_house和order.to_house。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 2015-11-16
      • 1970-01-01
      相关资源
      最近更新 更多