模型用户:
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对象,并将其友好列表中的另一个用户添加(或链接)到该对象。
例如:"User-1"从Shipment模型创建对象,并在这个过程中(在填写表单字段时)将"User-2"从他的友好列表(友谊模型对象)添加到该Shipment模型对象中。因此,最终的Shipment模型对象在某种程度上看起来像最后一个示例:
user.shipment.name
user.shipment.price
user.shipment.friend.name
自2004年5月5日起更新:做了大量的研究,并通过添加另一个模型找到了类似的解决方案,现在该应用程序看起来是这样的(更新很强):
型号用户:
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
型号发货_用户:
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的用户的名称,但对于"<%=@Shipping.User.friend(:id).name%>"部分,我得到了另一个错误:
NoMethodError in ShipmentsController#show
undefined method `friend' for #<User:0x007f1e400e8e08> Did you mean? friends friends=
首件friend
不是装运的关联。此外,目前还不清楚哪个用户朋友会提及。如果你能澄清这一点,将有助于提供更具体的答案。
根据您的代码判断,为什么不添加一个简单的friend_id
列来引用应该是该货物的朋友的用户呢?在这种情况下,您的belongs_to
看起来像:
添加friend_id、外键后。在发货模型中:
belongs_to :friend, class_name: "User"