Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Board Index:
- http://2ch.hk/pr/
- // Routes
- routes.rb:
- get ":tag", controller: "boards", action: "index"
- // Controllers
- controllers/boards.rb
- class BoardsController < BaseController
- def index
- // params - системная переменная в каждом запросе контроллера. Содержит в себе все поступившие через запрос параметры (в нашем случае: http://2ch.hk/<pr>/
- tag = params[:tag]
- // instance переменная чтобы она была доступна в View
- @posts = Board.where(tag: tag).posts
- // View который находится в views/boards/index.html.erb
- render "posts"
- end
- end
- // Models
- models/board.rb
- class Board < ActiveRecord::Base
- has_many :posts
- attr_reader :tag, :name
- end
- models/post.rb
- class Post < ActiveRecord::Base
- belongs_to :board
- attr_reader :title, :body
- // Атрибуты модели прозрачно описываются в миграции. Что опишешь в миграции то будет доступно в модели в качестве полей
- end
- // Migrations
- db/migrate/boards_migration.rb
- class BoardsMigrations < ActiveRecord::Migration
- def up
- create_table :boards do |table|
- table.string :name
- table.string :tag
- end
- end
- def down
- drop_table :posts
- end
- end
- db/migrate/posts_migrations.rb
- class Posts < ActiveRecord::Migration
- def up
- create_table :posts do |table|
- table.string :title
- table.string :body
- table.references :board
- end
- end
- def down
- drop_table :posts
- end
- end
- // Views
- views/boards/index.html.erb
- <% @posts.each do |post| %>
- <h1><%= post.title %></h1>
- <p><%= post.body %></p>
- <% end %>
Advertisement
Add Comment
Please, Sign In to add comment