0

I have done this a million times and yet I can't seem to figure out why it is not working now. I have a user model that has_one profile. The profile belongs_to the user model. In my profile controller, I am trying to access all the profiles that belong to a subset of users but I can't seem to. I have tried this:

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

I am getting the error that the method user is undefined. Yet, in views, I have called @profiles.user and it works fine. I have also tried:

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

but that does not work. Please help. Thanks.

EDIT:

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


class Profile < ActiveRecord::Base
    belongs_to :user
end
4

2 回答 2

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模型上被调用。

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

于 2013-11-08T23:09:27.533 回答
0

请按照以下步骤尝试,

   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
于 2013-11-08T19:49:19.733 回答