Сейчас на сайте

Сейчас 4 гостей онлайн

Поиск

Tag Cloud

Twitter oAuth и Cod... Баллада о г... сихи лирик... стихи лири... Динамическ... Домашняя с... Использова... Использова... Отправка с... Создание ф... Шепот посл... TinyMCE в Rails стихи лири... Быстрая ра... Пишем собс... Создание с... Установка ... Ностальгия... Москва-Бел... стихи лири... Стихи про п... Крылья сти... Создание п... Простой по... Создание п... Одинокий в... Гражданин ... Несчастный... Сонет стих... Отрезок ст... Врагу не сд... Предчувств... Поиск в ст... Использова... Смерть дву... Использова... Как сделат... Как сделат... Облако тег... Южная сере... Программна... Codeigniter в де... CodeIgniter: фор... проверка в... стихи лири... WEB fetcher(scrappe... Простой Twitt... стихи твор... стихи лири... Проверка п... Создание и ... Побег с Сол... Отправка SMS... MS VSTO 2007/Infusio... Установка R... Fckeditor в при... Степные тр... моя любовь. К твоим оз... Сомкнуть л... чтоб отдат... вот – вот ... еще не расс... Снег тишина и лу... и мира пово... что мой пос... Лишь ты. И т... ты любима ты чиста. Экспорт да... Я пью до дн... что нам теп... -Наш первый... Социальные... Социальные... Спит в можж... Воздух про... Стены рожденные ... эхо умрет. Неотправле... стихи лири... Он порезал... Боясь шагн... не осталос... Услышать з... Программир...

Программирование форума в Ruby on Rails с помощью plugina acts_as_threaded PDF Печать E-mail
09.02.2012 17:50

Форумы используются сейчас практически во всех приложениях. Здесь мы создадим форум, легко и просто .Далее все как обычно, пошагово

 

1. Создаем форум с помощью acts_as_threaded. Сейчас данный плагин отчего-то недоступен на странице проекта, но его несложно отыскать в Сети. Документация и ссылка находиться тут: http://oldwiki.rubyonrails.org/rails/pages/Acts_as_threaded Скачиваем и помещаем его в папку /vendors/plugins/

 

2. Создаем новую модель:

 

 

C:\myapp>ruby script/generate model ForumPost

exists app/models/

exists test/unit/

exists test/fixtures/

create app/models/forum_post.rb

create test/unit/forum_post_test.rb

create test/fixtures/forum_posts.yml

exists db/migrate

create db/migrate/20110711144245_create_forum_posts.rb

C:\myapp>

 

1. Редактируем файл модели:

 

class ForumPost < ActiveRecord::Base

acts_as_threaded

end

 

2. Редактируем файл миграции:

 

class CreateForumPosts < ActiveRecord::Migration

def self.up

create_table :forum_posts do |table|

table.column :name, :string, :limit => 50, :null => false

table.column :subject, :string, :limit => 255, :null => false

table.column :body, :text

table.column :root_id, :integer, :null => false, :default => 0

table.column :parent_id, :integer, :null => false, :default => 0

table.column :lft, :integer, :null => false, :default => 0

table.column :rgt, :integer, :null => false, :default => 0

table.column :depth, :integer, :null => false, :default => 0

table.column :created_at, :timestamp, :null => false

table.column :updated_at, :timestamp, :null => false

end

end

def self.down

drop_table :forum_posts

end

end

C:\>cd myapp

C:\myapp>ruby script/generate model ForumPost

exists app/models/

exists test/unit/

exists test/fixtures/

create app/models/forum_post.rb

create test/unit/forum_post_test.rb

create test/fixtures/forum_posts.yml

exists db/migrate

create db/migrate/20110711144245_create_forum_posts.rb

C:\myapp>rake db:migrate

(in C:/myapp)

== CreateForumPosts: migrating ===============================================

-- create_table(:forum_posts)

-> 0.0780s

== CreateForumPosts: migrated (0.0780s) ======================================

C:\myapp>

3. Снова редактируем файл модели форума, устанавливаем правила валидации:

 

class ForumPost < ActiveRecord::Base

acts_as_threaded

validates_length_of :name, :within => 2..50

validates_length_of :subject, :within => 5..255

validates_length_of :body, :within => 5..5000

end

 

4. Создаем контроллер форума:

 

C:\myapp>ruby script/generate controller Forum index reply show post create

exists app/controllers/

exists app/helpers/

create app/views/forum

exists test/functional/

exists test/unit/helpers/

create app/controllers/forum_controller.rb

create test/functional/forum_controller_test.rb

create app/helpers/forum_helper.rb

create test/unit/helpers/forum_helper_test.rb

create app/views/forum/index.html.erb

create app/views/forum/reply.html.erb

create app/views/forum/show.html.erb

create app/views/forum/post.html.erb

create app/views/forum/create.html.erb

C:\myapp>

 

5. Создаем методы в контроллере Forum:

 

def post

@page_title = 'Post to forum'

@post = ForumPost.new

end

def create

@post = ForumPost.new(params[:post])

if @post.save

flash[:notice] = 'Post was successfully created.'

redirect_to :action => 'index'

else

@page_title = 'Post to forum'

render :action => 'post'

end

end

Затем создаем форму post.rhtml:

<%= error_messages_for 'post' %>

<% form_tag :action => 'create' do %>

<%= hidden_field :post, :parent_id %>

<p><label for="post_name">Name</label><br/>

<%= text_field 'post', 'name' %></p>

<p><label for="post_subject">Subject</label><br/>

<%= text_field 'post', 'subject' %></p>

<p><label for="post_body">Body</label><br/>

<%= text_area 'post', 'body' %></p>

<%= submit_tag "Post" %>

<% end %>

И новый файл формы index.rhtml

<% if @posts.size > 0 %>

<div><%= link_to 'New post' , :action => 'post' %></div>

<p>

<%= display_as_threads @posts %>

</p>

<% else %>

There are no posts yet. <%= link_to 'Be the first one to post here' , :action => 'post' %>

<% end %>

<br/>

 

6. Редактируем файл helper app/helpers/forum_helper.rb и добавляем туда метод display_as_threads:

module ForumHelper

def display_as_threads(posts)

content = ''

for post in posts

url = link_to("#{h post.subject}", {:action => 'show', :id => post.id})

margin_left = post.depth*20

content << %(

<div style="margin-left:#{margin_left}px">

#{url} by #{h post.name} &middot; #{post.created_at.strftime("%H:%M:%S %Y-%M-%d") }

</div>)

end

content

end

end

 

 

7. Добавляем метод show Forum:

def show

@post = ForumPost.find(params[:id])

@page_title = "'#{@post.subject}'"

end

И файл типа вида:

<dl>

<dt>Name</dt>

<dd><%= h @post.name %></dd>

<dt>Subject</dt>

<dd><%= h @post.subject %></dd>

<dt>Body</dt>

<dd><%= h @post.body %></dd>

</dl>

<%= link_to 'Reply', :action => 'reply', :id => @post %> |

<%= link_to 'Back', :action => 'list' %>

8. Добавляем теперь новый метод reply в контроллере Форума:

 

def reply

reply_to = ForumPost.find(params[:id])

@page_title = "Reply to '#{reply_to.subject}'"

@post = ForumPost.new(:parent_id => reply_to.id)

render :action => 'post'

end

 

Весь исходный код контроллер Форума:

 

class ForumController < ApplicationController

require 'rubygems'

def index

@page_title = 'Forum'

@posts = ForumPost.paginate :page=> params[:page], :per_page => 20, :order => 'root_id desc, lft'

end

def reply

reply_to = ForumPost.find(params[:id])

@page_title = "Reply to '#{reply_to.subject}'"

@post = ForumPost.new(:parent_id => reply_to.id)

render :action => 'post'

end

def show

@post = ForumPost.find(params[:id])

@page_title = "'#{@post.subject}'"

end

def post

@page_title = 'Post to forum'

@post = ForumPost.new

end

def create

@post = ForumPost.new(params[:post])

if @post.save

flash[:notice] = 'Post was successfully created.'

redirect_to :action => 'index'

else

@page_title = 'Post to forum'

render :action => 'post'

end

end

end

 

Все, наш форму полностью работоспособен и готов к использованию.

 

0
Обновлено 10.02.2012 15:30
 

Добавить комментарий


Защитный код
Обновить