【问题标题】:How to get the association name in rails?如何在rails中获取关联名称?
【发布时间】:2014-07-12 22:24:50
【问题描述】:

我的 user.rb 模型文件中有以下关联代码

class User < ActiveRecord::Base
  has_many :sent_messages, class_name: 'ChatMessage', foreign_key: 'sender_id'
  has_many :received_messages, class_name: 'ChatMessage', foreign_key: 'receiver_id'
end

我想要 ChatMessage 模型中的一个方法,该方法应由以下触发

current_user.sent_messages
current_user.received_messages

该方法应该返回被调用的关联的名称。 例如:

class ChatMessage < ActiveRecord::Base
  after_find :get_association_name
  def get_association_name
    self.association_name // this should return sent_message or received_message depending on whether current_user.sent_messages or current_user.received_messages was called
  end
end

有没有办法在 Rails 中获取此关联名称? 任何帮助深表感谢。谢谢

【问题讨论】:

  • 你能告诉我们你在哪个班级有haS_many关联吗?请填写该代码。
  • 已更新代码..请检查

标签: ruby ruby-on-rails-3 callback associations


【解决方案1】:

我不确定你在找什么,但是

CurrentUser.reflect_on_all_associations(:has_many)

将给出一个包含所有 has_many 关联的数组。

【讨论】:

  • 您好,谢谢您的回复..您能再检查一下问题吗,我已经更新了
【解决方案2】:

我没有在这种情况下使用 AR 关联扩展,但你应该可以这样做:

has_many :sent_messages, class_name: 'ChatMessage', foreign_key: 'sender_id' do
  def get_association_name; 'sent_messages'; end
  # or, to make this more generic,
  # def get_association_name; proxy_association.reflection.name.to_s; end
end

并且该方法应该可以从您的关系中访问。如果您使用的是 Rails 4,您可以将通用版本提取到一个单独的模块中,以更简洁地扩展您的关联。见http://guides.rubyonrails.org/association_basics.html#association-extensions

编辑

试试:

has_many :sent_messages, class_name: 'ChatMessage', foreign_key: 'sender_id' do
  def and_set_type
    proxy_association.target.each do |msg|
      msg.update_attribute(:type, 'sent')
    end
    scoped
  end
end

然后使用current_user.sent_messages.and_set_type 访问您的sent_messages

【讨论】:

  • 您好,感谢您的回复..您能再检查一下问题吗,我已经更新了
  • 我认为您应该能够使用您的简单消息定义关联扩展;查看更新的答案。
  • 谢谢..会试试的
  • 我刚刚对其进行了测试,并使用一个选项更新了我的答案,以获取关联名称的字符串值。
  • 实际上,我的 chat_message 模型中有一个 attr_accessor :type,当使用 current_user.sent_messages 或 current_user.received_messages 检索对象时,我想将其设置为“已发送”或“已接收”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多