|
Продолжаем проект "Сообщество".
Запускаем скрипт миграции: C:\community>rake db:migrate == CreateGalleries: migrating ================================================ -- create_table(:galleries) -> 0.0625s == CreateGalleries: migrated (0.0625s) =======================================
C:\community>
После обновляем файл роутера config/routes.rb
ActionController::Routing::Routes.draw do |map| map.resources :sessions map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.showuser ":user", :controller => 'profile', :action => 'index' map.showprofile ":user/profile", :controller => 'profile', :action => 'show' map.editprofile ":user/profile/edit", :controller => 'profile', :action => 'edit' map.updateprofile ":user/profile/update", :controller => 'profile', ➥ :action => 'update' map.addavatar ":user/avatar/create", :controller => 'avatar', :action => 'create' map.resources :posts, :path_prefix => ":user" map.resources :galleries, :path_prefix => ":user" end
Связываем модели User и Gallery:
require 'digest/sha1'
class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken
validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100
validates_presence_of :email validates_length_of :email, :within => 6..100 #
Этот e-mail адрес защищен от спам-ботов, для его просмотра у Вас должен быть включен Javascript
validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message before_save :encrypt_password after_create :create_details has_one :detail has_one :avatar has_many :posts do def recent find(:all, :order => 'created_at desc', :limit => 6) end end has_many :galleries def name "#{first_name} #{last_name}" end
# HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :name, :password, :password_confirmation
# Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login.downcase) # need to get the salt u && u.authenticated?(password) ? u : nil end
def login=(value) write_attribute :login, (value ? value.downcase : nil) end
def email=(value) write_attribute :email, (value ? value.downcase : nil) end
def create_details self.create_detail end end
class Gallery < ActiveRecord::Base belongs_to :user validates_presence_of :user_id, :name end
28.Создаем новый ресурс Photo C:\community>ruby script/generate scaffold photo user_id:integer gallery_id:inte ger parent_id:integer content_type:string filename:string thumbnail:string size: integer width:integer height:integer created_at:datetime exists app/models/ exists app/controllers/ exists app/helpers/ create app/views/photos exists app/views/layouts/ exists test/functional/ exists test/unit/ exists test/unit/helpers/ exists public/stylesheets/ create app/views/photos/index.html.erb create app/views/photos/show.html.erb create app/views/photos/new.html.erb create app/views/photos/edit.html.erb create app/views/layouts/photos.html.erb identical public/stylesheets/scaffold.css create app/controllers/photos_controller.rb create test/functional/photos_controller_test.rb create app/helpers/photos_helper.rb create test/unit/helpers/photos_helper_test.rb route map.resources :photos dependency model exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/photo.rb create test/unit/photo_test.rb create test/fixtures/photos.yml exists db/migrate create db/migrate/20111009144947_create_photos.rb Затем запускаем скрипт миграции: C:\community>rake db:migrate rake/rdoctask is deprecated. Use rdoc/task instead (in RDoc 2.4.2+) == CreatePhotos: migrating =================================================== -- create_table(:photos) -> 0.0938s == CreatePhotos: migrated (0.0938s) ========================================== C:\community> Устанавливаем связь между моделями User и Photo:
require 'digest/sha1'
class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken
validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100
validates_presence_of :email validates_length_of :email, :within => 6..100 #
Этот e-mail адрес защищен от спам-ботов, для его просмотра у Вас должен быть включен Javascript
validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message before_save :encrypt_password after_create :create_details has_one :detail has_one :avatar has_many :posts do def recent find(:all, :order => 'created_at desc', :limit => 6) end end has_many :galleries has_many :photos def name "#{first_name} #{last_name}" end
# HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :name, :password, :password_confirmation
# Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login.downcase) # need to get the salt u && u.authenticated?(password) ? u : nil end
def login=(value) write_attribute :login, (value ? value.downcase : nil) end
def email=(value) write_attribute :email, (value ? value.downcase : nil) end
def create_details self.create_detail end end class Photo< ActiveRecord::Base belongs_to :user has_many :photos validates_presence_of :user_id, :name end Далее подключим attachment_fu к классу модели Photo
class Photo < ActiveRecord::Base has_attachment :content_type => :image, :storage => :file_system, :max_size => 2.megabytes, :resize_to => '640x360>', :thumbnails => { :thumb => '140x105>' } validates_as_attachment belongs_to :gallery belongs_to :user end
Обновляем файл роутера, помещаем туда новый ресурс /config/routes.rb:
ActionController::Routing::Routes.draw do |map| map.resources :sessions map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.showuser ":user", :controller => 'profile', :action => 'index' map.showprofile ":user/profile", :controller => 'profile', :action => 'show' map.editprofile ":user/profile/edit", :controller => 'profile', :action => 'edit' map.updateprofile ":user/profile/update", :controller => 'profile',:action => 'update' map.addavatar ":user/avatar/create", :controller => 'avatar', :action => 'create' map.resources :posts, :path_prefix => ":user" map.resources :galleries, :path_prefix => ":user" map.resources :photos, :path_prefix => ":user" end
29. Создадим новую галерею. Поместим новый метод new
class GalleriesController < ApplicationController def new @gallery = current_user.galleries.build end end Форма для добавления новой галлереи: <h1 class="section_header">Create A New Gallery</h1> <%= error_messages_for :gallery %> <% form_for(:gallery, :url => galleries_path(:user => current_user.login)) do |f| %> <p><b>Name</b><br /> <%= f.text_field :name %> </p> <p><b>Description</b><br /> <%= f.text_area :description %> </p> <p><%= submit_tag "Create" %> </p> <% end %> Закончим опцию с помощью метода create:
class GalleriesController < ApplicationController def new @gallery = current_user.galleries.build end def create @gallery = current_user.galleries.build(params[:gallery]) if @gallery.save redirect_to gallery_url(:user => current_user.login, :id => @gallery) else render :action => "new" end end end 30. Добавляем метод show для отображения выбранной галереи: class GalleriesController < ApplicationController def new @gallery = current_user.galleries.build end
def create @gallery = current_user.galleries.build(params[:gallery]) if @gallery.save redirect_to gallery_url(:user => current_user.login, :id => @gallery) else render :action => "new" end end def show @gallery = @user.galleries.find(params[:id]) end end Также создаем файл формы app/views/galleries/show.rhtml <h1 class="section_header"><%= @gallery.name %><h1> <% @gallery.photos.in_groups_of(3, false) do |photos| %> <ul class="thumbnails"> <% for photo in photos %> <li class="thumb"> <%= link_to(image_tag(photo.public_filename(:thumb) ) + '<br />' + ➥ photo.description, photo_path(:user => @user.login, :id => photo) ) %> </li> <% end %> </ul> <% end %> <% content_for :sidebar do %> <h1 class="section_header">Gallery Description<h1> <p><%= @gallery.description %></p> <% if show_admin_menu %> <hr /> <% form_for(:photo, :url => photos_path(:user => current_user.login), :html => { :multipart => true }) do |f| -%> <label for="photo_uploaded_data">Upload New Photo:</label> <%= f.file_field :uploaded_data, "size" => 15 %> <label for="photo_uploaded_data">Describe Photo:</label><br /> <%= f.text_field :description, "size" => 25 %> <%= f.hidden_field :gallery_id, :value => @gallery.id %> <%= submit_tag 'Upload Photo' %> <% end %> <% end %> <% end %>
31. Создаем новый метод index в классе контроллера Galleries: class GalleriesController < ApplicationController def index @galleries = @user.galleries.find(:all) end def new @gallery = current_user.galleries.build end
def create @gallery = current_user.galleries.build(params[:gallery]) if @gallery.save redirect_to gallery_url(:user => current_user.login, :id => @gallery) else render :action => "new" end end
def show @gallery = @user.galleries.find(params[:id]) end
end Далее создаем новый вид для отображения галерей app/views/galleries/index.rhtml :
<h1 class="section_header">Galleries<h1> <% @galleries.in_groups_of(3, false) do |galleries| %> <ul class="thumbnails"> <% for gallery in galleries %> <% unless gallery.photos.count == 0 %> <li class="thumb"> <%= link_to image_tag(gallery.photos.first.public_filename(:thumb)) + '<br />' + gallery.name + '<br />' + pluralize(gallery.photos.count, 'Photo'), gallery_path(:user => 'ealameda', :id => gallery.id) %> </li> <% else %> <li class="thumb"> <%= link_to gallery.name + '<br />' + pluralize(gallery.photos.count, 'Photo'), gallery_path(:user => 'ealameda', :id => gallery.id) %> </li> <% end %> <% end %> </ul> <% end %> <br /> <% content_for :sidebar do %> <p><%= link_to 'Create New Gallery', new_gallery_path %></p> <% end %> 32. Добавим 2 новых метода в контроллер Welcome,которые управляют вход пользователя:
class WelcomeController < ApplicationController
layout 'application'
before_filter :login_required skip_before_filter :get_user
def index end
def directory end end После редактируем файл роутера /config/routes.rb, где ставим в качестве ресурса по умолчанию контроллер Welcome: ActionController::Routing::Routes.draw do |map| map.home '', :controller => 'welcome', :action => 'index' map.resources :sessions map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.showuser ":user", :controller => 'profile', :action => 'index' map.showprofile ":user/profile", :controller => 'profile', :action => 'show' map.editprofile ":user/profile/edit", :controller => 'profile', :action => 'edit' map.updateprofile ":user/profile/update", :controller => 'profile',:action => 'update' map.addavatar ":user/avatar/create", :controller => 'avatar', :action => 'create' map.resources :posts, :path_prefix => ":user" map.resources :galleries, :path_prefix => ":user" map.resources :photos, :path_prefix => ":user" end 33. Создаем новый метод self.recent модели Post, который будет отображать последние введенные сообщения блога:
class Post < ActiveRecord::Base belongs_to :user before_filter :login_required
def self.recent find(:all, :order => 'Posts.created_at desc', :group => 'user_id', :limit => 7, :include => :user) end end Затем редактируем код метода index Welcome,чтобы отображать сообщения: class WelcomeController < ApplicationController layout 'application' before_filter :login_required skip_before_filter :get_user
def index @posts = Post.recent @galleries = @user = end
def directory end end После редактируем код файла вида app/views/welcome/index.rhtml этого метода:
<div class="blog"> <h1 class="section_header">Newest Blog Posts<h1> <% for post in @posts %> <h3> <%= link_to post.headline, post_path(:user => post.user.login, :id => post) %> </h3> <span class="added">Written by <%= post.user.name %></span> <p> <%= truncate(post.body.gsub(%r{</?.*?>}, ""), 130) %> <%= link_to "[Read More]", post_path(:user => post.user.login, :id => post) %> </p> <hr /> <% end %> </div> 34. Редактируем модель Photo, помещаем метод self.recent, показывающий последние галереи:
class Photo < ActiveRecord::Base has_attachment :content_type => :image, :storage => :file_system, :max_size => 2.megabytes, :resize_to => '640x360>', :thumbnails => { :thumb => '140x105>' } validates_as_attachment belongs_to :gallery belongs_to :user def self.recent find(:all, :order => 'Photos.created_at desc', :limit => 4, :conditions => 'parent_id is null', :group => 'galleries.user_id', :include => :gallery) end end
Редактируем код класса контроллера
class WelcomeController < ApplicationController layout 'application'
before_filter :login_required skip_before_filter :get_user
def index @posts = Post.recent @photos = Photo.recent @user = end
def directory end
end 35. Затем создаем новый метод в модели класса User self.random для отображения случайного пользователя: require 'digest/sha1'
class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken
validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100
validates_presence_of :email validates_length_of :email, :within => 6..100 #
Этот e-mail адрес защищен от спам-ботов, для его просмотра у Вас должен быть включен Javascript
validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message before_save :encrypt_password after_create :create_details has_one :detail has_one :avatar has_many :posts do def recent find(:all, :order => 'created_at desc', :limit => 6) end end has_many :galleries has_many :photos
def self.random users = User.find(:all) random = rand(User.count) users[random] end def name "#{first_name} #{last_name}" end
# HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :name, :password, :password_confirmation
# Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login.downcase) # need to get the salt u && u.authenticated?(password) ? u : nil end
def login=(value) write_attribute :login, (value ? value.downcase : nil) end
def email=(value) write_attribute :email, (value ? value.downcase : nil) end
def create_details self.create_detail end end 36. Редактируем код формы для отображения профиля пользователя app/views/welcome/index.rhtml:
<div class="blog"> <h1 class="section_header">Newest Blog Posts<h1> <% for post in @posts %> <h3> <%= link_to post.headline, post_path(:user => post.user.login, :id => post) %> </h3> <span class="added">Written by <%= post.user.name %></span> <p> <%= truncate(post.body.gsub(%r{</?.*?>}, ""), 130) %> <%= link_to "[Read More]", post_path(:user => post.user.login, :id => post) %> </p> <hr /> <% end %> </div> <% content_for :sidebar do %> <div class='about'> <h1 class="section_header">Have you met?</h1> <h3><%= link_to @user.name, showprofile_path(:user => @user.login) %></h3> <p><%= @user.detail.headline %></p> <p><%= image_tag show_avatar %></p> <p><%= @user.detail.about_me %></p> <p><%= link_to '[Learn More About Me]', showprofile_path(:user => @user.login) %></p> </div> <div class='gallery'> <h1 class="section_header">Newest Photos</h1> <% for photo in @photos %> <p class="thumb"> <%= link_to image_tag(photo.public_filename(:thumb)) + '<br />' + photo.gallery.name + '<br /> by ' + photo.gallery.user.name + '<br />', gallery_path(:user => photo.gallery.user.login, :id => photo.gallery) %> </p> <% end %> </div> <% end %> 37. После редактируем файл роутера config/routes.rb.Здесь установим правило для перенаправления запроса на страницу метода directory:
ActionController::Routing::Routes.draw do |map| map.home '', :controller => 'welcome', :action => 'index' map.resources :sessions map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.directory '/directory/:char', :controller => 'welcome', :action => 'directory', :char => 'A' map.showuser ":user", :controller => 'profile', :action => 'index' map.showprofile ":user/profile", :controller => 'profile', :action => 'show' map.editprofile ":user/profile/edit", :controller => 'profile', :action => 'edit' map.updateprofile ":user/profile/update", :controller => 'profile', :action => 'update' map.addavatar ":user/avatar/create", :controller => 'avatar', :action => 'create' map.resources :posts, :path_prefix => ":user" map.resources :galleries, :path_prefix => ":user" map Затем создаем метод directory, отображающий пользователей в алфавитном порядке: class WelcomeController < ApplicationController layout 'application' before_filter :login_required skip_before_filter :get_user
def index @posts = Post.recent @photos = Photo.recent @user = end
def directory @alphabet = ('A'..'Z').to_a @user = User.find(:first, :order => :random) @character = params[:char] @users = User.find(:all, :order => "last_name ASC", :conditions => ["last_name like ?", params[:char] + "%"]) end end Теперь создаем форму для отображения списка пользователей app/views/welcome/directory.rhtml
<h1 class="section_header">Alphabetical Index</h1> <div class="directory"> <% @alphabet.each do |letter| %> <% if letter == @character %> <span class="current"><%= letter %></span> <% else %> <%= link_to letter, directory_path(:char => letter), :class => "letter" %> <% end %> <% end %> </div> <hr/>
<% for user in @users %> <div class="result"> <div class="userImage"><%= image_tag show_small_avatar(user) %></div> <div class="userInfo"> <strong>Name: </strong><%= user.name %><br /> </div> <div class="userActions"> <%= link_to "View", showprofile_path(:user => user.login) %> </div> </div> <% end %>
<% content_for :sidebar do %> <div class='about'> <h1 class="section_header">Have you met?</h1> <h3><%= link_to @user.name, showprofile_path(:user => @user.login) %></h3> <p><%= @user.detail.headline %></p> <p><%= image_tag show_avatar %></p> <p><%= @user.detail.about_me %></p> <p><%= link_to '[Learn More About Me]', showprofile_path(:user => @user.login) %></p> </div> <% end %> 38. Редактируем файл, помещаем туда новую навигацию:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Church Family Pages</title> <link rel="stylesheet" href="http://yui.yahooapis.com/2.2.0/build/reset-fonts-grids/reset-fonts-grids.css" type="text/css"> <%= stylesheet_link_tag 'styles' %> </head> <body> <div id="doc2" class="yui-t7"> <div id="hd"> <h1>Church Family Pages<h1> </div>
<div id="bd"> <div class="yui-g navigation"> <a href="/">Home</a> | <a href="/directory">Directory</a> | <a href="/logout">Logout</a> </div> <div class="yui-gc"> <div class="yui-u first"> <%= yield %> </div> <div class="yui-u"> <div class ='sidebar'><%= yield :sidebar %></div> </div> </div> </div> <div id="ft"> <% if logged_in? %> <div class="admin_menu"> <%= link_to 'Your Page', showuser_path(:user => current_user.login) %> <%= link_to 'Edit your Profile', editprofile_path(:user => current_user.login) %> <%= link_to 'Create Blog Post', new_post_path(:user => current_user.login) %> <%= link_to 'Manage Photo Galleries', galleries_path(:user => current_user.login) %> </div> <% end %> </div> </div> </body> </html> 39. Устанавливаем новый плагин acts_as_commentable чтобы создать опцию для комментирования. После запускаем скрипт миграции: C:\community>ruby script/generate migration add_comments exists db/migrate create db/migrate/20111009165430_add_comments.rb
C:\community>
После редактируем файл скрипта миграции db/migrate/20111009165430_add_comments.rb:
class AddComments < ActiveRecord::Migration def self.up create_table :comments, :force => true do |t| t.column :title, :string, :limit => 50, :default => "" t.column :comment, :string, :default => "" t.column :created_at, :datetime, :null => false t.column :commentable_id, :integer, :default => 0, :null => false t.column :commentable_type, :string, :limit => 15, :default => "", ➥ :null => false t.column :user_id, :integer, :default => 0, :null => false end add_index :comments, ["user_id"], :name => "fk_comments_user" end def self.down drop_table :comments end end
Запускаем скрипт миграции: C:\community>rake db:migrate rake/rdoctask is deprecated. Use rdoc/task instead (in RDoc 2.4.2+) == AddComments: migrating ==================================================== -- create_table(:comments, {:force=>true}) -> 0.2500s -- add_index(:comments, ["user_id"], {:name=>"fk_comments_user"}) -> 0.4219s == AddComments: migrated (0.6719s) ===========================================
C:\community> 40. Добавляем в класс модели Post acts_as_commentable: class Post < ActiveRecord::Base belongs_to :user acts_as_commentable before_filter :login_required
def self.recent find(:all, :order => 'Posts.created_at desc', :group => 'user_id', :limit => 7, :include => :user) end
end После добавим этот же плагин в модель класса Photo:
class Photo < ActiveRecord::Base acts_as_commentable has_attachment :content_type => :image, :storage => :file_system, :max_size => 2.megabytes, :resize_to => '640x360>', :thumbnails => { :thumb => '140x105>' } validates_as_attachment belongs_to :gallery belongs_to :user def self.recent find(:all, :order => 'Photos.created_at desc', :limit => 4, :conditions => 'parent_id is null', :group => 'galleries.user_id', :include => :gallery) end end
41. Помещаем новую форму для отображения комментариев в файл views/post/show.html:
<%= javascript_include_tag 'tiny_mce/tiny_mce' %> <%= javascript_include_tag 'tinyconfig' %>
<div class="blog"> <h1 class="section_header"><%= @post.headline %><h1> <%= @post.body %> <p><span class="added">written on <%= @post.created_at.to_s(:long) %></span></p> <hr /> <% if show_admin_menu %> <%= link_to 'Edit This Post', edit_post_path(:user => @user.login, :id => @post) %><br /> <%= link_to 'Destroy This Post', post_path(:user => @user.login, :id => @post), :confirm => 'Are you sure?', :method => :delete %> <% end %> </div>
<% if @post.comments.any? %> <div id ="comments"> <h1 class="section_header">Comments</h1> <ol id="comment-list"> <% for comment in @post.comments %> <% user = comment.user %> <li> <div class="comment-head"> <div class="comment-author-details"> <h3><div class="user-img"><%= link_to(image_tag(user.small_avatar), showuser_path(:user => user)) %></div> <%= link_to user.name, showuser_path(:user => user) %> posted</h3> </div> </div>
<div class="comment-body"> <div class="comment-body-paragraph"><p><%= comment.comment %></p></div> </div> <p class="comment-link small"><em> </em></p> </li> <% end %> </ol> </div> <% end %>
<div id="comment_form"> <h1 class="section_header">Post a Comment</h1> <% form_for :comment, :url => addcomment_post_path do |c| %> <p> <label for "comment_body">Comment:</label><br /> <%= c.text_area 'comment', "cols" => 70, "rows" => 5 %> <%= c.hidden_field 'user_id', :value => current_user.id %> </p> <p> <%= submit_tag 'Add Comment' %> </p> <% end %> </div>
<% content_for :sidebar do %> <div class='about'> <h1 class="section_header">About Me</h1> <p><%= @user.detail.headline %></p> <p><%= image_tag show_avatar %></p> <p><%= @user.detail.about_me %></p> <p><%= link_to '[Learn More About Me]', showprofile_path(:user => @user.login) %></p> </div> <% end %> После этого редактируем файл роутера, подключая туда комментарии:
ActionController::Routing::Routes.draw do |map| map.home '', :controller => 'welcome', :action => 'index' map.resources :sessions map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.directory '/directory/:char', :controller => 'welcome', :action => 'directory', :char => 'A' map.showuser ":user", :controller => 'profile', :action => 'index' map.showprofile ":user/profile", :controller => 'profile', :action => 'show' map.editprofile ":user/profile/edit", :controller => 'profile', :action => 'edit' map.updateprofile ":user/profile/update", :controller => 'profile', :action => 'update' map.addavatar ":user/avatar/create", :controller => 'avatar', :action => 'create' map.resources :posts, :path_prefix => ":user",:member => { :addcomment => :post } map.resources :galleries, :path_prefix => ":user",:member => { :addcomment => :post } map.resources :photos, :path_prefix => ":user" end 42. Создаем новые методы addcomment для контроллеров Posts и Photo:
class PostsController < ApplicationController before_filter :login_required
def new @post = current_user.posts.build end def show @post = @user.posts.find(params[:id]) end
def edit @post = current_user.posts.find(params[:id]) end
def create @post = current_user.posts.build(params[:post]) if @post.save redirect_to showuser_path(:user => @user.login) else render :action => "new" end end
def update @post = current_user.posts.find(params[:id]) if @post.update_attributes(params[:post]) redirect_to showuser_path(:user => @user.login) else render :action => "edit" end end
def destroy @post = current_user.posts.find(params[:id]) @post.destroy redirect_to showuser_url(:user => @user.login) end def addcomment post = current_user.posts.find(params[:id]) comment = Comment.new(params[:comment]) post.add_comment comment redirect_to post_path(:user => params[:user], :id => post) end end class PhotosController < ApplicationController def index @photos = Photo.find(:all) end
def show @photo = Photo.find(params[:id]) end
def new @photo = Photo.new end
def edit @photo = Photo.find(params[:id]) end
def create @photo = Photo.new(params[:photo]) if @photo.save redirect_to gallery_url(:user => current_user.login, :id => @photo.gallery_id) else render :action => "new" end end
def update @photo = Photo.find(params[:id]) if @photo.update_attributes(params[:photo]) redirect_to photo_url(@photo) else render :action => "edit" end end
def destroy @photo = Photo.find(params[:id]) @photo.destroy redirect_to galleries_url(:user => @user.login) end def addcomment photo = Photo.find(params[:id]) comment = Comment.new(params[:comment]) post.add_comment comment redirect_to photo_path(:user => params[:user], :id => photo) end end Это все.
|