Ruby on rails: Adding 2 references of a single model to another model

此生再无相见时 提交于 2019-12-23 05:25:15

问题


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

Lets say I have 2 models named House and Order.

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

Is there any specific way to this in 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


回答1:


In create orders migration file:

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

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

In your views:

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

Enjoy!




回答2:


Add this answer just in case Surya's code doesn't work - I'm used to having to specify the 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

Just make sure you have two attributes on Order - one being from_id and another to_id. From now on you can call order.from_house and order.to_house.



来源:https://stackoverflow.com/questions/25611918/ruby-on-rails-adding-2-references-of-a-single-model-to-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!