ruby on rails - Query a has many model, after querying the belongs to model -



ruby on rails - Query a has many model, after querying the belongs to model -

i have 2 models user , product , user has_many :products. given set of users, how find products created them.

question: find products available sale , beingness sold near particular address. first finding users live near by. querying products beingness sold users. checking availability on products. not work. why so?

in controller index action have:

@users = user.near(params[:nearby], 20) @users.find_each |user| @products << user.products_selling # <-- not work end @products = @products.available

product.rb model

belongs_to :seller, class_name: 'user', foreign_key: :user_id, dependent: :delete scope :available, -> { where(availableforsale: true) }

user.rb model

has_many :products_selling, class_name: 'product'

error

undefined method `<<' nil:nilclass

please note- if alter << = works products of lastly user queried on not users (obviously).

please help

@users = user.near(params[:nearby], 20) @products = product.where(["user_id in (?)", @users.map(&:id)]).available

fixing code below, (but not thought query within loop)

@products = [] # initialize empty array before insert @users.each |user| @products << user.products_selling.to_a # insert array of products rather relation # @products array of arrays. end @products = @products.flatten.select(&:availableforsale) # flatten array, , select ones availableforsale

ruby-on-rails ruby ruby-on-rails-4

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -