Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of the has_many 'conditions' option in Rails 4?

Can someone tell me what is the equivalent way to do the following line in Rails 4?

has_many :friends, :through => :friendships, :conditions => "status = 'accepted'", :order => :first_name 

I tried the following:

has_many :friends, -> { where status: 'accepted' }, :through => :friendships , :order => :first_name 

But I get the following error:

Invalid mix of scope block and deprecated finder options on ActiveRecord association: User.has_many :friends 
like image 931
medBouzid Avatar asked Dec 01 '13 01:12

medBouzid


People also ask

What is Activerecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Has_and_belongs_to_many?

2.6 The has_and_belongs_to_many Association A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. This association indicates that each instance of the declaring model refers to zero or more instances of another model.

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is dependent destroy in Rails?

what is dependent :destroy. Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.


1 Answers

Needs to be the second arg:

class Customer < ActiveRecord::Base   has_many :orders, -> { where processed: true } end 

http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many

RESPONSE TO UPDATE:

Put the order inside the block:

has_many :friends, -> { where(friendship: {status: 'accepted'}).order('first_name DESC') }, :through => :friendships 
like image 140
Kaleidoscope Avatar answered Oct 18 '22 11:10

Kaleidoscope