如何将模型1关系添加到由model-3创建的model-2对象?

时间:2016-04-04 23:08:11

标签: ruby-on-rails ruby-on-rails-4

模特用户:

has_many :shipments, dependent: :destroy
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, :class_name => 'Friendship', 
                                 :foreign_key => 'friend_id'
has_many :inverse_friends, :through => :inverse_friendships, :source => :user

模特友谊:

belongs_to :user
belongs_to :friend, :class_name => 'User'

模型装运:

belongs_to :user

我需要用户创建一个Shipment-object并将另一个用户从其友好列表添加(或以某种方式链接)到该对象。

例如:" User-1"从Shipment-model创建对象,并在此过程中(填充表单字段时)添加" User-2"从他的朋友列表(友谊模型对象)到该Shipment-model对象。所以最终的Shipment-model对象看起来就像最后一个例子:

user.shipment.name
user.shipment.price
user.shipment.friend.name

从05.04更新: 做了大量研究,发现添加另一个模型的类似解决方案,现在应用程序看起来像这样(更新变得强大):

模特用户:

has_many :shipments, dependent: :destroy
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, :class_name => 'Friendship', 
                                 :foreign_key => 'friend_id'
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_many :shipment_users
has_many :shipments, through: :shipment_users

模特友谊:

belongs_to :user
belongs_to :friend, class_name: "User"

模型装运:

belongs_to :user
belongs_to :friend, class_name: "User"
has_many :shipment_users
has_many :users, through: :shipment_users

Model Shipment_User:

belongs_to :shipment
belongs_to :user

创建货件对象的表格:

<%= form_for(@shipment, html: { multipart: true, role: "form"}) do |f| %>
  <%= f.collection_check_boxes :friend_id, User.all, :id, :name do |cb| %>
    <% cb.label(class: "checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
  <% end %>
<% end %>

货件视图文件:

<h4><%= @shipment.user(:id).name %></h4>
<h4><%= @shipment.user.friend(:id).name %></h4>

现在结果: 在表单中,Rails创建了所有现有用户并将它们放在复选框中,但是没有任何反应,在视图文件中它显示了创建Shipping的用户的名称,但部分&#34;&lt;%= @ shipment.user .friend(:id).name%&gt;&#34;我收到另一个错误:

NoMethodError in ShipmentsController#show
undefined method `friend' for #<User:0x007f1e400e8e08> Did you mean? friends friends=

1 个答案:

答案 0 :(得分:1)

首先关闭friend不是发货关联。此外,还不清楚哪个用户朋友会参考。如果您能澄清这一点,将有助于提供更具体的答案。

根据您的代码判断,为什么不添加一个简单的friend_id列来引用应该是该货件的朋友的用户?在这种情况下,您的belongs_to将如下所示:

添加你的friend_id,外键后。在装运模型中:

belongs_to :friend, class_name: "User"