ラベル views の投稿を表示しています。 すべての投稿を表示
ラベル views の投稿を表示しています。 すべての投稿を表示

2010/05/07

ternary operator を使いこなす

コードを見直してると、こんなのがよくあります。
if self.something
  something += x
else
  something = 0
end
これ、ternary operator 使ったら綺麗なのになー、といつも思うので備忘録
self.something ? something += x : something = 0
# condition ? do_true : do_false
View でも便利
%lt;%= session[:user_id] ? @user.name : "<a href='...' >ログインしてください</a>" %>
ちなみに、日本語では三項演算子というらしい。知らなかった。。。

2010/04/10

検索フォームにコダワル

いろんなところで使いそうなので、検索フォームの作り方をまとめてみた。(突っ込みどころは沢山あると思います。)

まず view
<% form_tag request.path, :method => 'get' do %>
<table>
 <tr>
  <td><%= t('common.created_at') %></td>
  <td><%= calendar_date_select_tag(:created_from, params[:created_from], :time => false)%> - <%= calendar_date_select_tag(:created_to, params[:created_to], :time => false)%></td>
 </tr>
 <tr>
  <td><%= t('common.keyword') %></td>
  <td><%= text_field_tag :keyword, params[:keyword], :size => 30 %> ID <%= text_field_tag :id, params[:id], :size => 10 %></td>
 </tr>
 <tr>
  <td>sort_by</td>
  <td><%= select_tag(:sort_by, options_for_select([['created_at', 'created_at'], ['updated_at', 'updated_at'], ['login_at', 'login_at'], ['ID', 'id'] ], 'created_at' ) ) %> <%=select_tag(:sort_dir, options_for_select([[t('common.asc'), 'ASC'], [t('common.desc'), 'DESC']], 'DESC'))%> 
  </td>
 </tr>
 <tr>
  <td></td>
  <td><%= submit_tag t('common.search_with_conditions') %> <input type="reset" value="Reset!"></td>
 </tr>
</table>
<%end %> 
リセットボタンは便利。また、select_tag にオプションを渡す場合は options_for_select を使用。
<%= select_tag(:sort_by, options_for_select([['created_at', 'created_at'], ['updated_at', 'updated_at'], ['login_at', 'login_at'], ['ID', 'id'] ], 'created_at' ) ) %>
selected = 'created_at' を指定している。

controller
    @users = User.full_search(params[:keyword], params[:page], :id => params[:id],
      :created_from => params[:created_from], :created_to => params[:created_to],
      :sort_by => params[:sort_by], :sort_dir => params[:sort_dir]
      )
model
メソッドには自由にパラメータを渡せるように options={} を使う
  def self.x_search(search, page, options = {})
    sql = "((display_name like '%#{search}%') OR (profile like '%#{search}%') OR (first_name like '%#{search}%') OR (last_name like '%#{search}%') OR (email like '%#{search}%') OR (mobile like '%#{search}%'))"

    if options[:id] && options[:id] != ""
      sql << " AND id = '#{options[:id]}'" 
    end

    if options[:created_from] && options[:created_from] != ""
      from = Time.parse(options[:created_from]).to_s(:db)
      # If timezone conversion required use Time.zone.parse(options[:created_to]).utc.to_s(:db)
      sql += " AND created_at >= '#{from}'"
    end
  
    if options[:created_to] && options[:created_to] != ""
      to = Time.parse(options[:created_to]).to_s(:db) 
      sql += " AND created_at <= '#{to}'"
    end
  

    if options[:sort_by] && options[:sort_by] != "" && options[:sort_dir] && options[:sort_dir] != ""
      order = options[:sort_by] + " " + options[:sort_dir]
    else
      order = 'created_at DESC'
    end    

    paginate(:per_page => 30, :page => page, :conditions => sql, :order => order)
  end

2010/02/17

Tips on views

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title><%= h(yield(:title) || "Untitled") %></title>
    <%= stylesheet_link_tag "/jqtouch/jqtouch.min.css", "/jqtouch/themes/apple/theme.min.css" %>
    <%= javascript_include_tag "/jqtouch/jquery.1.3.2.min.js", "/jqtouch/jqtouch.min.js", "mobile" %>
    <%= yield(:head) %>
  </head>
  <body>
    <div class="current">
      <%- if show_title? -%>
      <div class="toolbar">
        <%= link_to "Back", nil, :class => "back" unless current_page? root_path %>
        <h1><%=h yield(:title) %></h1>
        <%= link_to "Full Site", root_url(:mobile => 0), :class => "button", :rel => "external" %>
        <%= yield(:toolbar) %>
      </div>
      <%- end -%>
      
      <% unless flash.empty? %>
        <div class="info">
        <%- flash.each do |name, msg| -%>
          <%= content_tag :div, msg, :id => "flash_#{name}" %>
        <%- end -%>
        </div>
      <% end %>
    
      <%= yield %>
    </div>
  </body>
</html>
<% content_for :head do %>
  <%= stylesheet_link_tag 'projects' %>
<% end %>
http://railscasts.com/episodes/199-mobile-devices

2010/01/11

一つのフォームに複数の submit ボタンを入れる

たまに一つのフォームに複数の submit ボタンをつけて、どれをクリックするかでロジックを分けたい場合がある。 application.js
function submitWithValueAndConfirm(formid, commitValue, text)
{
 if (window.confirm(text)) {
     var objForm = document.getElementById(formid);
  objForm.commit_value.value = commitValue;
  objForm.submit();
 } else {
  return false;
 }
}


view
<% form_for :req, @req, :url => {:action => :update}, :html => {:method => :put, :id => "action"} do |f| %>
    <input type="hidden" name="commit_value" />
    <%= f.submit "CONFIRM", :onClick => ("return submitWithValueAndConfirm('action','confirm', 'Will do. Okay?');") %>
<%= f.submit "KILL", :onClick => ("return submitWithValueAndConfirm('action','kill', 'Will delete. Okay?');") %>
    <%= f.submit I18n.t('btn_something'), :onClick => ("return submitWithValueAndConfirm('action','confirm', '" + I18n.t('something') + "');") %>
<% end %>
上で return confirm はポップアップメッセージ用。:onclick を使用すると、:confirm が使えないため。

controller
case params[:commit_value]
  when "confirm"
    ...
  when "kill"
    ...
  when "something"
    ...
end

因みに、リンクでフォームをサブミットする方法

<% form_for ([:user, @user], :url => {:action => :create}, :html => {:name => :login}) do |f| %>
   ...
   <a href='#' onclick="document.login.submit();" >Login</a>

<% end %>