【问题标题】:profile belongs_to user but can't access user in controller个人资料属于用户,但无法访问控制器中的用户
【发布时间】:2013-11-08 19:09:20
【问题描述】:

我已经这样做了一百万次,但我似乎无法弄清楚为什么它现在不起作用。我有一个 has_one 配置文件的用户模型。配置文件属于用户模型。在我的个人资料控制器中,我试图访问属于用户子集的所有个人资料,但我似乎无法访问。我试过这个:

def index
    if params[:tag]
        @profiles = Profile.user.tagged_with(params[:tag])
    else
        @profiles = Profile.all
    end
end

我收到方法用户未定义的错误。然而,在视图中,我调用了@profiles.user,它工作正常。我也试过:

def index
    if params[:tag]
        @profiles = Profile.users.tagged_with(params[:tag])
    else
        @profiles = Profile.all
    end
end

但这不起作用。请帮忙。谢谢。

编辑:

class User < ActiveRecord::Base
    has_one :profile
    acts_as_taggable
end


class Profile < ActiveRecord::Base
    belongs_to :user
end

【问题讨论】:

  • 如果关系是 has_one 那么你就可以像第一个例子那样使用 user 了。我很想看看你的模型定义。也很高兴看到您的 tagged_with 方法
  • 在 User.rb 和 Profile.rb 中给我们您的模型关联声明。你acts_as_taggable你的模型吗?
  • 仅仅因为你有一个user 字段作为你的Profile 定义的一部分,并不意味着你在Profile 上有类方法userusers
  • 我添加了模型。用户模型有acts_as_taggable。 profile 方法没有,因为它没有与之关联的标签。丹,tagged_with 不是我的方法,它是acts_as_taggable_on gem 的一部分。
  • 彼得,刚刚看了加载错误的问题。我看不出与我的问题有任何联系。不过还是谢谢。

标签: ruby-on-rails tags ruby-on-rails-4 rails-activerecord acts-as-taggable-on


【解决方案1】:

这是因为user 不是Profile 的类方法,它是一个实例方法。还有

你需要:

def index
 if params[:tag]
   @profiles = Profile.find(params[:profile_id]).user#whatever else you're trying to do
 else
   @profiles = Profile.all
end

但是根据您在后续行动中所说的话,您需要一些东西,您可以从加入个人资料中选择用户,然后致电tagged_with

也许

def self.users_with_profiles
 query = <<-SQL
    SELECT u.*
      FROM users AS u
      JOIN profiles AS p
        ON p.user_id = u.id
  SQL

  find_by_sql(query)
end

然后

def index
  @profiles = User.users_with_profile.tagged_with(params[:tag]).map {|user| user.profile }
end

或者它可能更简单

def index
  @profiles = User.joins(:profile).tagged_with(:params).map { |user| user.profile }
end

这将返回 Profiles,这是我假设您正在寻找的,因为它在您的 Profile 模型上调用。

如果这不能让你一直到那里,我希望它至少能让你更接近

【讨论】:

    【解决方案2】:

    按照以下步骤尝试,

       def index
          if params[:tag]
            # first find out users having tag = params[:tag]
            users = User.tagged_with(params[:tag])
            # collect ids of those users assume user_ids = array of ids
            user_ids = users.map(&:id)
            # then make query on profile model
            @profiles = Profile.where(user_id: user_ids) # get list of profiles            
          else
            @profiles = Profile.all
          end
       end
    

    【讨论】:

    • 谢谢,但这并没有让我了解用户。我需要联系用户,以便我可以使用acts_as_taggable 方法。
    • KD12,您的答案不包括 tagged_with 方法。您的评论还将针对尚未创建个人资料的用户,这不是我想要的。不过感谢您的帮助,我认为已经接近了。
    • 在问题中,您提到 Profile.users.tagged_with(params[:tag]) 它返回具有个人资料的用户或具有 params[:tag] 的用户的个人资料?
    • 我认为它会返回用户,但它没有返回任何东西。
    • 索引方法配置文件或用户的返回值是多少?你提到了@profiles 变量并且你想要@profiles 中的用户?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多