ruby-rails笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QQlwx/article/details/75675626

1.rails new blog

2.cd blog

3.rails server

4.rails generate controller Welcome index

5.rails routes

6.rails generate model Article title:string text:text

7.rails db:migrate

8.rails generate controller Comments

9.外键

Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id, order_id). These are the fields that Active Record will look for when you create associations between your models.

10.数据库的操作

Creating Active Record Models It is very easy to create Active Record models. All you have to do is to subclass the ApplicationRecord class and you’re good to go:

class Product < ApplicationRecord
end

This will create a Product model, mapped to a products table at the database. By doing this you’ll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the products table was created using an SQL statement like:

CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);

Following the table schema above, you would be able to write code like the following:

p = Product.new
p.name = "Some Book"
puts p.name # "Some Book"

1.增

 test = Test.create(name: "David")
test = Test.new
test.name = '222'
test.save

2.读

users = User.all
user = User.first
david = User.find_by(name: 'David')
users = User.where(name: 'David', 
occupation: 'Code Artist').order
(created_at: :desc)

3.更新


user = User.find_by(name: 'David')
user.name = 'Dave'
user.save
user = User.find_by(name: 'David')
user.update(name: 'Dave')

4.删除

user = User.find_by(name: 'David')
user.destroy

猜你喜欢

转载自blog.csdn.net/QQlwx/article/details/75675626