Guest User

Untitled

a guest
Mar 13th, 2015
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.83 KB | None | 0 0
  1. Board Index:
  2. http://2ch.hk/pr/
  3.  
  4. // Routes
  5. routes.rb:
  6.  
  7. get ":tag", controller: "boards", action: "index"
  8. // Controllers
  9.  
  10. controllers/boards.rb
  11.  
  12. class BoardsController < BaseController
  13.   def index
  14.     // params - системная переменная в каждом запросе контроллера. Содержит в себе все поступившие через запрос параметры (в нашем случае: http://2ch.hk/<pr>/
  15.     tag = params[:tag]
  16.     // instance переменная чтобы она была доступна в View
  17.     @posts = Board.where(tag: tag).posts
  18.     // View который находится в views/boards/index.html.erb
  19.     render "posts"
  20.   end
  21. end
  22.  
  23. // Models
  24.  
  25. models/board.rb
  26.  
  27. class Board < ActiveRecord::Base
  28.   has_many :posts
  29.   attr_reader :tag, :name
  30. end
  31.  
  32. models/post.rb
  33.  
  34. class Post < ActiveRecord::Base
  35.   belongs_to :board
  36.   attr_reader :title, :body
  37.   // Атрибуты модели прозрачно описываются в миграции. Что опишешь в миграции то будет доступно в модели в качестве полей
  38. end
  39.  
  40. // Migrations
  41.  
  42. db/migrate/boards_migration.rb
  43.  
  44. class BoardsMigrations < ActiveRecord::Migration
  45.   def up
  46.     create_table :boards do |table|
  47.       table.string :name
  48.       table.string :tag
  49.     end
  50.   end
  51.  
  52.   def down
  53.     drop_table :posts
  54.   end
  55. end
  56.  
  57. db/migrate/posts_migrations.rb
  58.  
  59. class Posts < ActiveRecord::Migration
  60.   def up
  61.     create_table :posts do |table|
  62.       table.string :title
  63.       table.string :body
  64.  
  65.       table.references :board
  66.     end
  67.   end
  68.  
  69.   def down
  70.     drop_table :posts
  71.   end
  72. end
  73.  
  74. // Views
  75.  
  76. views/boards/index.html.erb
  77.  
  78. <% @posts.each do |post| %>
  79.   <h1><%= post.title %></h1>
  80.   <p><%= post.body %></p>
  81. <% end %>
Advertisement
Add Comment
Please, Sign In to add comment