---
title: "rails activerecord join查询 include 和 find_or_create find_or_initialize"
author: "夜鸣猪"
date: "2011-12-02T23:45:36Z"
tags: []
categories: ["编程语言"]
slug: "rails-activerecord-join-include-find-or-create-find-or-initialize"
draft: false
lastmod: "2011-12-06T09:17:57Z"
id: 1290342
url: "https://hlee.iteye.com/blog/1290342"
---

```ruby
Student.joins(:schools).where(:schools => { :category => 'public' })
Student.joins(:schools).where('schools.category' => 'public' )
```




```ruby

# No 'Summer' tag exists
Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")

# Now the 'Summer' tag does exist
Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")

# Now 'Bob' exist and is an 'admin'
User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }

```


小差别在于是否创建



```ruby

winter = Tag.find_or_initialize_by_name("Winter")
winter.persisted? # false

```



```ruby

productproperty = ProductProperty.find_or_create_by_product_id(product.id) { |u| u.property_id => property_id, u.value => d[descname] } )

```



```ruby

conditions = { :product_id => product.id, 
               :property_id => property.id,
               :value => d[descname] }

pp = ProductProperty.find(:first, :conditions => conditions) || ProductProperty.create(conditions) 

```



```ruby

down vote
	

If you want to search by multiple attributes, you can use "and" to append them. For example:

productproperty = ProductProperty.find_or_create_by_product_id_and_property_id_and_value(:product_id => product.id, :property_id => property.id, :value => d[descname])

```


dynamic finder style