発展課題の解答を用意してみました。
一解答例にすぎませんが、参考にしてください。

急いで作ったので間違ってたらツッコんでください。

:per_page に指定した数字に合わせて、前のン件, 次のン件としてみよう。

ActionController::Pagination::Paginator#items_per_pageを使って、
$ vi app/views/bbs/list.rhtml

<%= link_to "前の#{@comment_pages.items_per_page}", { :page => @comment_pages.current.previous }
            if @comment_pages.current.previous %>
<%= link_to "次の#{@comment_pages.items_per_page}", { :page => @comment_pages.current.next }
            if @comment_pages.current.next %>

リファレンスマニュアルでは、Attributesのところにあって、なんの説明もないので、見つけにくいかもしれません。

http://localhost:3000/bbs/edit/1 と言う風に直接アクセスすると、誰の発言でも自由に編集できてしまう。コントローラから使ってないメソッドを削除して、編集ができないようにしよう。

app/controllers/bbs_controller.rb中の、edit,show,updateメソッドを削除し、verify の行にある、:updateも消す。
app/views/bbs/edit.rhtmlapp/views/bbs/show.rhtml二つのファイルも消します。

投稿フォームを /list/bbs の一番上に移動して、直接投稿できるようにしてみよう。

app/views/bbs/list.rhtmlの上の方に、

<div>
  <%= start_form_tag :action => 'create' %>
    <%= render :partial => 'form' %>
    <%= submit_tag "投稿" %>
  <%= end_form_tag %>
</div>

を追加。

# app/controllers/bbs_controller.rb
   def list
     @comment_pages, @comments = paginate :comments, :per_page => 10, :order => 'created_at desc'
     @comment ||= Comment.new # ||= は、create から呼ばれた時に@commentを上書きしないため。
   end
  
   def create
     @comment = Comment.new(params[:comment])
     if @comment.save
       flash[:notice] = 'Comment was successfully created.'
       redirect_to :action => 'list'
     else
       list # この行追加
       render :action => 'list' # エラーがあった場合の戻り先を変更
     end
   end

   # new アクションは削除

app/views/bbs/new.rhtmlも消してしまいましょう。

Commentにvalidatesを追加して、必須項目を決めよう。

title, body, name を必須項目に、email, homapage は空じゃなかったら、正規表現で判定をしています。 email の方の正規表現は、 validates_format_of のサンプルコードから、homepageの方は先頭がhttp://またはhttps://かをチェックしています。 凝りたい人はどうぞ。

# app/models/comment.rb
class Comment < ActiveRecord::Base
  validates_presence_of [:title, :body, :name]
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :if => proc{|comment| !comment.email.blank?}
  validates_format_of :homepage, :with => %r|^https?://|, :if => proc{|comment| !comment.homepage.blank?}
end

また、次のようなテストコードを書いて、

$ rake test:units

を実行することで、正しそうに動いているかチェックできます。

テストコード↓を書いてから、実装↑を書くと、TDD.

# test/unit/comment_test.rb
require File.dirname(__FILE__) + '/../test_helper'
  
class CommentTest < Test::Unit::TestCase
  def setup
    @comment = Comment.new(:title => 'hi!', :body => 'hello!', :name => 'bob', :email => "", :homepage => "")
  end
  
  def test_validation
    assert_valid @comment
  end
  
  def test_presence_on_title
    @comment.title = nil
    @comment.save
    assert_not_nil @comment.errors.on(:title)
  end
  
  def test_presence_on_body
    @comment.body = nil
    @comment.save
    assert_not_nil @comment.errors.on(:body)
  end
  
  def test_presence_on_name
    @comment.name = nil
    @comment.save
    assert_not_nil @comment.errors.on(:name)
  end
  
  def test_email
    @comment.email = 'bob@rails6.com'
    @comment.save
    assert_valid @comment
  
    @comment.email = 'bob.rails6.com'
    @comment.save
    assert_not_nil @comment.errors.on(:email)
  end
  
  def test_homepage
    @comment.homepage = 'https://bob.rails6.com'
    @comment.save
    assert_valid @comment
  
    @comment.homepage = 'http://bob.rails6.com'
    @comment.save
    assert_valid @comment
  
    @comment.homepage = 'ftp://bob.rails6.com'
    @comment.save
    assert_not_nil @comment.errors.on(:homepage)
  end
end

削除キーを入力しないと削除できないようにしてみよう。

まず、migration でdelete_key というカラムを追加します。

$ script/generate migration AddDeleteKey
      exists  db/migrate
      create  db/migrate/004_add_delete_key.rb
# vi db/migrate/004_add_delete_key.rb
class AddDeleteKey < ActiveRecord::Migration
  def self.up
    add_column :comments, :delete_key, :string
  end
  
  def self.down
    remove_column :comments, :delete_key
  end
end

$ rake db:migrate

次に、投稿フォームに、削除キー入力フィールドを作り、

<!-- app/views/bbs/_form.rhtml -->
<p><label for="comment_delete_key">削除キー</label><br/>
<%= text_field 'comment', 'delete_key'  %></p>

削除ボタンのとなりにテキストフィールドを追加。

<!-- app/views/bbs/list.rhtml -->
     <td>投稿日時:<%= comment.created_at.strftime("%Y/%m/%d %H:%M:%S") %></td>
     <td>
       <%= start_form_tag :action => 'destroy', :id => comment %>
       <%= text_field_tag 'delete_key' %>
       <%= submit_tag "削除" %>
       <%= end_form_tag %>
     </td>

その値を受けて、保存された削除キーと、入力された削除キーが一致しないとdestroyしないように、コントローラを書き換える。

# app/controllers/bbs_controller.rb
   def destroy
     c = Comment.find(params[:id])
     c.destroy if !c.delete_key.blank? && c.delete_key == params[:delete_key]
     redirect_to :action => 'list'
   end

今回のテストコードは、コントローラのテストなので、以下の通り。

まず、テストデータを二つ用意。 片方は、削除キー’bob123’、片方は削除キーなし(削除できない)

# test/fixtures/comments.rb
bob:
  id: 1
  title: hi
  body: hello
  name: bob
  delete_key: bob123
undeletable:
  id: 2
  title: hi
  body: hello
  name: bob
  delete_key: ''
# test/functional/bbs_controller_test.rb
require File.dirname(__FILE__) + '/../test_helper'
require 'bbs_controller'
  
# Re-raise errors caught by the controller.
class BbsController; def rescue_action(e) raise e end; end
  
class BbsControllerTest < Test::Unit::TestCase
  # テスト用データである、fixture をロード。(上で書いたやつ)
  fixtures :comments
  
  # test_* の前に実行される。
  def setup
    @controller = BbsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end
  
  # 削除キーを指定しないと削除されない
  def test_destroy_without_delete_key
    id = comments(:bob).id
    assert_not_nil Comment.find(id)
    post :destroy, :id => id
    assert_not_nil Comment.find(id)
  end
  
  # 削除キーを指定すると削除される
  def test_destroy_with_delete_key
    id = comments(:bob).id
    assert_not_nil Comment.find(id)
    post :destroy, :id => id, :delete_key => comments(:bob).delete_key
    assert_raise(ActiveRecord::RecordNotFound) {
      Comment.find(id)
    }
  end
  
  # 削除キーが空のレコードは、空の削除キーで削除できない
  def test_destroy_record_having_empty_delete_key
    id = comments(:undeletable).id
    assert_not_nil Comment.find(id)
    post :destroy, :id => id, :delete_key => comments(:undeletable).delete_key
    assert_not_nil Comment.find(id)
  end
end

This entry was posted on 2007-01-22 20:26:00 GMT and カテゴリ , . You can follow any response to this entry through the Atom feed. or a trackback from your own site.

タグ ,


トラックバック

トラックバックリンク:
http://blog.netswitch.jp/trackbacks?article_id=4853

コメント

  1. ばば 2007-01-25 00:14:21 GMT:

    レッスンお疲れ様でした! ちゃんとフォローが!!!m(  )m ありがたく、メモさせてもらいます^^;

  2. Etenuesty 2011-06-22 22:50:18 GMT:

    Hi great post we have going here! Mars Venus Coaching

  3. steathesolley 2011-06-24 20:54:30 GMT:

    im prospering to this passage fetich called a friday fest with my cocker tonight and idk what it is,there like stands and building blocks, but if u advised of, plz disbosom oneself me so i can have a good shilly-shally!!! lol -THANKS!! :)

  4. invoizict 2011-07-16 10:54:27 GMT:

    moral gonna phrase hello…

  5. osteomitummaf 2011-11-25 12:38:11 GMT:
  6. osteomitummaf 2011-11-25 12:38:14 GMT:
  7. osteomitummaf 2011-11-25 12:38:18 GMT:
  8. osteomitummaf 2011-11-25 12:38:24 GMT:
  9. NoobleeSM 2011-11-29 13:46:14 GMT:

    Hi everyone!
    The most beautiful women in the world, you must see.
    Free adult webcam: click here

  10. zinassswerzz 2012-01-05 07:28:19 GMT:

    Люди!!! Я нашла уникальный метод, с помощью которого я полностью излечила своего мужа от АЛКОГОЛИЗМА (!) История моя длинная, не стану тут её полностью описывать, а кому интересно - добро пожаловать на мою страницу, где я всё подробно рассказываю: http://t1234.ru/index-nat.htm !

  11. carpinteyrosvi 2012-03-17 14:32:33 GMT:

    Passion,though a bad regulator,is a powerful spring.

  12. BerKneect 2012-04-19 01:34:22 GMT:

    Even when all users of your family see the other each day, developing is still needed. This is certainly essentially the simplest way to fortify the bond one of the family members and even help make your marriage to each other stronger. Really it is good some thing outdoors but if the weather conditions isn’t that superior or maybe it can be pouring birds outdoors, you can think about several types of household activities and activities which will seriously make every person feel good. This is a good alternate you could think about. Here are some of the games or the things to do which can be done inside.Hide and seek is just about the preferred online games previously competed and this also can definitely be exercised indoors. Another person should be an “itInches who definitely are accountable of in search of other members of your family who definitely are concealing. The first one that is to be located without pressingVersusgetting to your home starting will then become the up coming Init.In . But if you’re imagine that this may not be a great option, you’ll be able to investigate charade and that is a different indoors online game. During this sport, ultimately, there should be two groups. It will have a user that could rebel the phrase which is written on certificates while the folks will be in-control of wondering the phrase. The team most abundant in issues might be announced because winner.Other than hide and seek and charade, a lot of avenues of unit card and games may also be one of several best options you could investigate. Games include things like Menagerie, Older House maid, Going, Natural stone, Slapjack and much more. For board games, you are able to go with Scrabble, Mentally stimulating games, Monopoly, Family members Feud and Pieces. Since you also have a lot of options to think about, less costly select one which you imagine is absolutely pleasurable.However, if you think that trying to play the game titles that have been already stated won’t be sufficient, you can select other activities which almost all of the family members have pursuits in. For example, if you love in order to cookOrfarrenheit to be able young kids, you’ll be able to makes activity that allows you to attachment with your loved ones. You’ll be able to designate each associate to undertake a specific area of the bakingOrpreparing procedure to ensure that all people will like. Guarantee that all people gets to take part in this sort of task. Once food is cooked or maybe the cake is cooked, then you can certainly eat it alongside one another with all the relatives. Everybody will obviously be delighted to have the berry of their toil. Other than preparing food/this baking, it’s also possible to take into consideration several other activities like painting, dance, vocal skills, looking at, seeing motion pictures and several extra.These are incredibly solutions for rapport with the fam however, these are truly efficient. You do not have for you spend a lot of cash since these uncomplicated issues can unquestionably get contentment to all people especially if the household is total. It’s actually not actually crucial that these materials ought to be done every day. Once per week or maybe a few times per 30 days will do.

  13. BerKneect 2012-04-19 20:51:42 GMT:

    Even if all customers of ones own see the other on a daily basis, relationship remains necessary. It is generally the easiest method to improve the hyperlink on the list of close relatives and also create your relationship to each other stronger. It really is great to behave out-of-doors but if your conditions isn’t that good or if it is raining outside the house, you can consider different kinds of interior online games and actions that can actually make every person feel good. This is a good option that you could take into account. Below are some of the game titles or actions which can be done indoors.Hide and seek is just about the most popular online games ever before played out this also can definitely be done indoors. An individual ought to be an InitIn . who will be dependable of looking for other close relatives who definitely are trying to hide. Website which is to be found with out touching/hitting your property foundation will likely then function as the future Init.Half inch But if you are think that this may not be a good solution, you may check into charade and that is a different inside online game. In this recreation, ultimately, there must be two clubs. You will see a member that could act on the phrase which is written on a piece of paper even though the other members are usually in-control of wondering your message. The group with the most things should be proclaimed since the winner.Other than hide and go seek and charade, a lot of avenues of credit card and games may also be among the list of best alternatives that you may explore. Games include things like Menagerie, Older Maid, Running, Natural stone, Slapjack and many other. For games, you’ll be able to choose Scrabble, Chess, Monopoly, Loved ones Feud and Checkers. Because you have plenty of choices to observe, you simply need to choose the brains behind you would imagine is really enjoyable.However, if you find that playing the activities that had been already stated are not suitable, it is possible to decide on other items which the majority of the family have likes and dislikes in. In particular, job in order to cookPerfarrenheit in order your family, then you can certainly makes activity in an effort to bond with the family. You’ll be able to assign each member to try and do a certain section of the preparing your receipeeAndpreparing practice so that absolutely everyone will enjoy. Ensure that everyone extends to attend these activity. Once cuisine is made or cake is prepared, then you can eat it jointly because of the family members. Every person will really be thrilled you can eat the fresh fruits of these toil. As well as food preparationVersuscooking, additionally you can look at various other pursuits like painting, belly dancing, singing, reading, seeing videos and many far more.These are extremely simple ways to attachment with your family but the are really effective. You shouldn’t have for you personally devote lots of money since these simple points can definitely deliver contentment to anyone particularly if the family members are total. It isn’t definitely crucial that these items should be carried out on a daily basis. Once weekly or perhaps a few times each month will perform.

  14. BerKneect 2012-04-20 11:49:08 GMT:

    Even if all users of ones own see one another each day, connection continues to be essential. This really is essentially the best way to strengthen the link on the list of family members as well as create your marriage to one another healthier. Really it is great some thing out-of-doors but should the climatic conditions is certainly not very good or if it is really pouring birds exterior, you can think about several types of indoor activities and activities which will truly make absolutely everyone feel happy. This is a good alternative you could think about. The following are some of the games and the exercises you can do in the house.Hide and seek is probably the most in-demand game titles actually experienced which really can be practiced inside. Somebody ought to be an In .itIn . who will be accountable of trying to get other loved ones who definitely are hiding. The first one that’ll be discovered without having pressingPeraccomplishing the house foundation are able to function as up coming Init.” But should you be believe this is not a very good alternative, you may investigate charade that’s a different inside video game. Within this game, ideally, there ought to be two squads. There will be a part that will make a scene the idea of that is certainly composed on a piece of paper while the individuals are typically in-management of wondering the word. The c’s with more details are able to be stated because success.Aside from hide and go seek and charade, a large variety of minute card and games may also be one of several best alternatives that you could check into. Card games incorporate Menagerie, Older Cleaning service, Moving, Jewel, Slapjack and many more. For games, you are able to go for Scrabble, Chess, Monopoly, Household Feud and Checkers. Since you have a lot of options to consider, you just need to opt for the brains behind you feel is very enjoyment.On the other hand, if you feel enjoying the video games which were mentioned above is definately not up to scratch, you can opt for alternative activities which almost all of the relatives have likes and dislikes in. By way of example, if you like cookingOrmake so as your son or daughter, then you can definitely get this to action so as to relationship with the family. You can delegate each member to undertake some the main preparingPerpreparing approach so that absolutely everyone will enjoy. Guarantee that every person actually reaches attend this sort of action. Whenever the food is made or maybe the dessert is baked, then you can definitely try to eat it alongside one another together with the family members. All people will definitely be satisfied you can eat the fruits with their labour. In addition to preparing foodPerthe baking, also you can look at various other activities like art work, dancing, music and singing, looking at, seeing movies and plenty of far more.These are merely extremely solutions for connect with your family nevertheless these are actually effective. You don’t have for you invest a lot of cash simply because easy issues can surely deliver enjoyment to every person specifically family is full. It isn’t really needed that these products ought to be done each day. Once per week or possibly a rare occasions per month are going to do.

  15. Groorkery 2012-05-28 07:56:54 GMT:

    Women’s wellness in present instances is most important. As of today, most women are energetic, imaginative, raise personal skills, coping with your home and raising young children. There isn’t a discipline in which the woman won’t brałaby shares. Thus, priority should be to care for their own personal well being. Normally, the exhaustion that makes their bodies have less resistance, it is rather very easy to catch a battery, virus. Ladies significantly more more often than not have infections of one’s pubic place. Typically this is often connected to the insufficient hygiene, and with very poor hygiene. It comes about also that women have no education and learning about cleanliness, intimate places. The topic is very embarrassing. It is not effortless to speak about it, in particular if you have these types of a problem. Using sanitary napkins painless, it could actually gdzie kupić miód manuka trigger inflammation. In heat and humid setting germs multiply extraordinarily efficiently. Females have to adjust the pad up every last two several hours. You need to utilize the antibacterial products and solutions, anti-viral, which block formation of irritation and also other problems. Our markets has by now appeared in goods that satisfy like situation. Their use is recommended by health and fitness businesses nationwide. Be certain to inform adult females about how they really should choose treatment of exclusive health and fitness, system and future. It ought to be mentioned that the setting is at current greatly polluted: air, food items, water. You ought to educate most women that delivering further detrimental substances into your entire body is purely irrational. You have to begin to consciously use of cosmetics, beauty chemistry as well as other steps that do not have natural ingredients.

  16. FebyFurorolla 2012-07-03 09:38:27 GMT:

  17. Preofeboype 2012-08-03 10:47:53 GMT:

    If you are to begin with handling a possible consumer, the very first thing they might listen to will be the communication in your answering device. cbfillergibberillicbx qrqzxwyxnc Have your down-line talk aided by the applicant to determine whether they is actually a very good prospect to your group or not.

  18. naturistimage icons 2012-09-11 02:40:23 GMT:

    In it something is. Earlier I thought differently, thanks for the help in this question.

    P.S. Please review our icons for Windows 8