kohanaバージョン3.xで、リダイレクトするには
Request::instance()->redirect('/foo/bar/1');
kohanaバージョン3.xで、リダイレクトするには
Request::instance()->redirect('/foo/bar/1');
kohanaというphpフレームワークを触り始めました。MVCパターンなのでいろんなところで結構Railsと似ていますが、コード量が明らかにRailsより多くてまだ慣れてません。さすがにRailsやってから他の言語やフレームワークを触るとキツイです。
kohanaにはデフォルトでmodulesにuserguideが付いてます。ローカルでもガイドのドキュメントやAPIを参照できるため結構便利です。
bootstrap.phpの中に’userguide’を検索してコメントアウトします。
例えばbase_urlが’myapp’の場合は: http://localhost/myapp/userguide/docs になります。
内容としては公式サイトのhttp://kohanaframework.org/guide/about.kohanaと同じになります。
プロジェクトに検索機能を追加しようとする。
git checkout -b add-search
=> ブランチ'add-search'を作成し、それに乗換
// ファイル修正
git add .
git commit -am "Done"
=> 修正ファイルをコミット、コミットメッセージは"Done"
git checkout master
=> masterブランチに乗換
git merge add-search
=> add-searchでの修正内容をマージ
git push
=> サーバにpush
requestがajaxかどうかを判断するのは、とても簡単です。
# in controller
if request.xhr?
...
end
xhrはXMLHttpRequestの略称です。XHRについては下記の記事を参照してください。 今更のAjax基本:XMLHttpRequestについて
Rails: default_scopeを使った場合注意しておきたいことArticleモデルがあるとします。ブログの記事は普通最新の順番で並んでまのでこんなdefault_scopeを定義したかもしれません。
# in Article model
default_scope :order => "articles.created_at DESC"
これで普通にArticle.allとかfindのときはデフォルトで作成日時が最新のものから並びますが Article.firstとArticle.lastにも影響があります。 つまり
Article.first # <Article id:999, ...>
Article.last # <Article id:1, ..>
考えてみれば当たり前のことですが、念のため覚えておきましょう。
PostとCommentのModelがあってPostが複数のCommentを持ってます。やりたいのはPostの表示画面(show view)でCommentを削除するリンクを作成ことです。
まずPostとCommentのModel、及びroutes.rbの設定を理解しましょう。
# post model
has_many :comments
# comment model
belongs_to :post
# routes.rb
resources :posts do
resources :comments
end
Viewのerbファイルでは下記のようなリンクを作成します。
<% @article.comments.each do |comment|
<%= comment.content %>
<%= link_to "Delete", article_comment_path(@article, :comment_id => comment), :method => :delete %>
<% end %>
これはcomments_controllerのdestroyアクションを呼ぶのでdestroy actionを作成する必要があります。
# in comments_controller.rb
def destroy
comment = Comment.find(params[:comment_id]
comment.destroy
redirect_to request.referer
end
:comment_idはviewで設定するパラメータ名と一致すればOKです。
Userモデルにどのカラムを定義したっけ、と言う場合schema.rbをいちいちチェックしないで済む方法があります。それがCarlos Brando氏が作ってくれたRuby on RailsのTextMate Bundleです。
これは元々のDr. Nic氏のruby-on-rails-tmbundleをForkして作ったものなので、従来の機能は保ちつつ新しい便利な機能が追加されました。
例えばUserモデルの変数user, @user, @@userなどの後ろでAlt(Option) + Spaceを押すと利用可能な属性がリストされます。なかなか便利です。
mkdir -p ~/Library/Application\ Support/TextMate/Bundles
cd ~/Library/Application\ Support/TextMate/Bundles
git clone git://github.com/carlosbrando/ruby-on-rails-tmbundle.git "Ruby on Rails.tmbundle"
osascript -e 'tell app "TextMate" to reload bundles'
本家サイト:http://github.com/carlosbrando/ruby-on-rails-tmbundle