markdown ActiveRecord的

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown ActiveRecord的相关的知识,希望对你有一定的参考价值。

## ActiveRecord
* `active record`: design pattern for relational databases
* `ActiveRecord`: RAILS implementation of the design pattern for relational databases!
* retrieves objects to manipulate(CRUD) them, not just static rows

```ruby
user = User.new
user.first_name = ''
user.save #SQL insert

user.delete #SQL delete
```

## ActiveRelation
* known as `Arel`
* Simplifies database queries through the use of chaining methods 

---

## Generating a Model
* from root: `rails g modelName` (singular name)
    * creates the associated db migration file (table), migrations are PLURAL!!
    * Inherits from `ActiveRecord::Base`
    * creates file in `app/model`, model are SINGULAR!!!
* If you have altered the model name in the database, from `users` to say `admin_users`,
you can specify in the model that youhave changed model name: `self.table_name = 'admin_users'`
* **ActiveRecord automatically provides `attr_accessor`s for each field in the model's db! NO
NEED TO REWRITE THEM!**
---

### Rails console
* `rails c` or  `bundle exec rails c` in root of rails app
* To specify which environment to change into: `rails c production`, `**development** is default!

---

## Creating Records
* `new`/`save`:
    * Instantiate
    * Set values
    * Save
  
```ruby
subject = Subject.new

subject.new_record?   #is it a new object? (not in db)
subject.name = "Example 1"

#for faster attribute assignment: MASS ASSIGNMENT
subject = Subject.new(name: "Example1", position: 1, visibible: true)

#finally, save the record to the database:
subject.save
#Outputs the SQL used to save the record, RETURNS either true(saved) or false(not saved)
#Adds the id field 

subject.new_record? #false, its in the db already
```

* `create`:

```ruby
subject = Subject.create(name: "Example1", position: 1, visibible: true)
#RETURNS the object the was saved to the DB
```

---

## Updating a Record
* `find`/`save` method:
    * find the record
    * set values
    * save
* `find`/`update_attributes` method:
    * find the record
    * set values and then save all at once!

```ruby
subject = Subject.find(1) #find with id=1

subject.name = "Initial example" #set value
subject.save  #SQL that is run using update method

#Using mass assignment:
subject = Subject.find(2)
subject.update_attributes(name: "Blah", position: 2, visible: true)
#runs another update SQL and returns true or false
```

---

## Deleting a Record
* `find`/`destroy` method

```ruby
subject = Subject.find(2)
subject.destroy
#returns the object that was destroyed
```

---

## Using REST to delete
* As of HMTL5, `delete` and `patch` requests are no longer valid to be used in forms!
* Ensure that you have a `destroy` action in your model controller that performs the deletion:

```ruby
def destroy
  @movie.destroy
  redirect_to ..., :notice => "Has been deleted!"
end
```

* Next, in your view template:

```ruby
<%= link_to("Delete", movie_path(movie), method: :delete, :data => {:confirm => "Really?"}) %>
```

* When you specify `method: :delete` and `:data => ...`, this is using some JavaScript that is
built in to rails!
    * The method delete will submit a 'delete' request (will use a 'GET' request if JS is
    disabled)

---

## Finding Records

```ruby
#primary key finder, returns object or error
subject.find(3) #finds subject with id of 3

#dynamic finder
subject.find_by_id(1) #returns nil if not found or the object if found
subject.find_by_any_valid_database_column_name()

#class method that finds all records
Subject.all #returns array with the collection of subjects

Subject.first #returns first item
Subject.last  #returns last item
```

* `order(arg)`: can be ordered by any column in the database table
* Use the notation below for when you have multiple tables with the same column name:
    * `order(table_name.column_name ASC/DESC)`
    * Example: `order("subjects.created_at ASC")`
* More recent for **Rails 5**:
    * `order(:position)`
    * `order(position: asc)`
    * `order("position ASC")`
* `limit(integer)`: reduces the amount of results returned from the query by integer
* `offset(integer)`: how much results to skip over before returning the results
* all 3 methods can be chained together!

```ruby
subjects = Subject.where(visible: true, position: 1)

subjects = Subject.where(["visible = ?", true])
```

以上是关于markdown ActiveRecord的的主要内容,如果未能解决你的问题,请参考以下文章

markdown ActiveRecord查询

markdown 禁用ActiveRecord for Rails 4,5

markdown ActiveRecord的地方の句の条件を动的にしたい

markdown ActiveRecord的にデフォルト値を设定する

markdown ActiveRecord的で范囲指定,大なり小なり比较

markdown ActiveRecord的の多重ネストをeager_load