我有3个相关对象:Group,Cipher,User。 密码既属于组又属于用户。用户也直接属于一个组。
群组的“显示”视图显示包含所有密码的群组。
我希望显示拥有每个密码的用户的名字,但它会引发错误undefined method 'first_name' for #<Group:0x007fa3f4a038a0>
这是Show view extract:
<table class="table table-striped table-condensed">
<tr align="left">
<th><%= t('Cipher') %></th>
<th><%= t('User') %></th>
<th><%= t('EndOfLife') %></th>
<th><%= t('UpdatedBy') %></th>
<th><%= t('UpdatedAt') %></th>
</tr>
<% @group.ciphers.order("updated_at").each do |child_object| %>
<tr align="left">
<td valign="top"> <%=child_object.key%> </td>
<td valign="top"> <%=child_object.user.first_name%> </td>
<td valign="top"> <%=child_object.valid_until%> </td>
<td valign="top"> <%=child_object.updated_by%> </td>
<td valign="top"> <%=child_object.updated_at%> </td>
</tr>
<% end%>
</table>
</div>
以下是群组模型:
class Group < ApplicationRecord
has_many :users
has_many :ciphers, :inverse_of => :user, :dependent => :destroy
accepts_nested_attributes_for :ciphers, :reject_if => :all_blank, :allow_destroy => true
以下是密码模型:
class Cipher < ApplicationRecord
#Filters
before_save { self.cipher_hash = (BCrypt::Password.create(key+group.name)).split(//).last(32).join }
#Validations
validates :key, :valid_until, :group_id, :user_id, presence: true
validates :key, length: {maximum: 100}
#Relations
belongs_to :group
belongs_to :user
end
以下是用户模型:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :zxcvbnable
#Filters
before_save { self.email = email.downcase }
#Validations
validates :name, :first_name, :group_id, presence: true, length: {maximum: 100}
#Relations
belongs_to :group
has_many :ciphers
end
感谢您的帮助! 端
答案 0 :(得分:0)
组的未定义方法'first_name':0x007fa3f4a038a0
使用inverse_of
,您正在设置双向关联,因为fisrt_name
不适用于Group
,它吐出了那个错误。
<强> 解决方案: 强>
只需删除inverse_of
class Group < ApplicationRecord
has_many :users
has_many :ciphers, :dependent => :destroy
accepts_nested_attributes_for :ciphers, :reject_if => :all_blank, :allow_destroy => true
end