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

2010/10/07

nested_attributes で error_messages_for のエラーメッセージがうまくローカライズされない。

Just trying to enable correct i18n for error_messages for using nested_attributes. Used this patch but moved to an initializer instead.

Rails 3.0.0.beta4 をいじっているときのこと。。。

nested_attributes を使って親モデルと子モデルを同時に編集する際、error_messages_for を使ってバリデーションのエラーメッセージを吐き出してるんですが、なぜか子モデルのエラーだけがローカライズされない。
例:
class User < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts

  validates_presence_of :name
end

class User < ActiveRecord::Base
  belongs_to :user

  validates_presence_of :title

end
で、
Posts title は必須です
名前は必須です
みたいに出力されてしまう。
運よくAnton Bangratzさんがパッチを書いてくれていた。Anton さんありがとうー!!
でも、パッチするのは嫌だったので、config/initializer/errors_i18n.rb と適当なファイルを作って、下記のように。。。
ActiveModel::Errors.module_eval do

  def full_messages
    full_messages = []

    each do |attribute, messages|
      messages = Array.wrap(messages)
      next if messages.empty?

      if attribute == :base
        messages.each {|m| full_messages << m }
      else
        # attr_name = attribute.to_s.gsub('.', '_').humanize
        attr_name = convert_name(attribute.to_s) 
        attr_name ||= attribute.to_s.gsub('.', '_').humanize        
        attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
        options = { :default => "%{attribute} %{message}", :attribute => attr_name }

        messages.each do |m|
          full_messages << I18n.t(:"errors.format", options.merge(:message => m))
        end
      end
    end

    full_messages
  end

  def convert_name(name)
    default = nil
    if name =~ /(.+)\.(.+)/
      base_name = $1
      attribute = $2
      base = ActiveSupport::Dependencies.constantize(base_name.camelize)
      if (base.respond_to? :model_name)
        default = "#{base.model_name.human} #{base.human_attribute_name(attribute.to_sym, :default => attribute.humanize)}"
      end
    end
    default 
  end  
  
end
因みに、ActiveModel::Errors::ClassMethods.module_eval do では Name Error になった。なぜだ?

2010/04/19

fieldWithErrors div でレイアウトが崩れてしまう件

フォームで、activerecord error があると、対象の入力フィールドのレイアウトが崩れてしまう件。 問題は、エラーのあるフィールドが fieldWithErrors という div でくくられてしまうこと。 initializer を作るか、environment.rb に次を入れると、div が span に変わる
config/initializers/errors.rb
ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| "<span class=\"fieldWithErrors\">#{html_tag}</span>" }
ついでに errors.css とか編集するといいかも
.fieldWithErrors {
  padding: 2px;
  background-color: red;
}
↓
.fieldWithErrors input, .fieldWithErrors select, .fieldWithErrors textarea {
  border: 2px solid red;
}

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/04/01

accepts_nested_attributes_for : 親モデルのフォームで子モデルも編集する方法

Service モデルが ServiceFile モデルと association で繋がっている場合。。。 ※ Railscasts 参照

models/service.rb

has_many :service_files, :dependent => :destroy
accepts_nested_attributes_for :service_files, 
    :reject_if => lambda { |a| a[:uploaded_data].blank? }, 
    :allow_destroy => true

models/service_files.rb

belongs_to :service

/service/new.html.erb & /service/edit.html.erb

<% form_for([:pro, @service], :url => {:action => :create},:html => {:multipart => true})  do |f| %>
  <!-- 子モデルにアップロードデータがあるので、multipart を指定 -->
  <% f.fields_for :service_files do |builder| %>
    <%= render "service_file_fields", :f => builder %>
  <% end %>
  <p><%= link_to_add_fields "Add", f, :service_files %></p>
<% end %>

_service_file_fields.html.erb

<div class="fields">
 <%= f.file_field :uploaded_data %>
 <%= link_to_remove_fields "<img src='/images/icons/cross.png'/>", f %>
</div>
※ application.js, application_helper.rb のメソッドは Railscasts 参照

はまったこと

undefined method `reflect_on_association' for NilClass:Class
・・・が
問題は<%= link_to_add_fields t('common.add_obj', :obj => t('file.singular')), f, :service_files %> に正しいクラスを渡してなかった。

<% form_for(@service, :url => {:action => :create},:html => {:multipart => true}) do |f| %>

を下に変えたら問題なし。(service は pro のネームスペース下)

< <% form_for([:pro, @service], :url => {:action => :create},:html => {:multipart => true}) do |f| %>

2010/03/18

Reading in the product language table

While loading the list of products on Jzool.com I naturally wanted to load the associated translation which is stored in a different table.

The best way to do this to use eager loading which is a cool thingie you do when you want to read associated tables in one go.

So, in the Product model I do this:

 has_many :product_languages, :dependent => :destroy
 has_one :t, :class_name => 'ProductLanguage',
   :conditions => ['locale = ?', I18n.locale],
   :select => 'id, product_id, name, short'

The "t" stands for "translated". Just wanted to keep it short. I could very well do has_many :ts by the way.

Now, in my paginated search method I use the include.

 def self.search(search, page)
   paginate :include => :t, :per_page => 20, :page => page,
            :conditions => ['name like ?', "%#{search}%"], :order => 'created_at desc'
 end

And then I can just call the translated name by doing:

<%= @product.t.name %>
However, this actually ends up generating two sql statements. Here's an example using two models - Category and CategoryLanguage where the latter holds the localized name of the category.
def localized_children
Category.find :all, :conditions => ['categories.parent_id = ? and categories.display = ?', self.id, true],
   :order => 'categories.sort_id asc',
   :select => 'categories.id, categories.name, categories.parent_id', :include => :t
end
This results in the following two sql statements
[4;35;1mCategory Load (1.0ms) [0m   
[0mSELECT categories.id, categories.name, categories.parent_id FROM `categories` WHERE (categories.parent_id = 307 and categories.display = 1) ORDER BY categories.sort_id asc [0m
[4;36;1mCategoryLanguage Load (1.0ms) [0m    [0;1mSELECT id, category_id, name FROM `category_languages` WHERE (`category_languages`.category_id IN (308,313,480,310,309,311,504,312) AND (locale = 'en'))
So it seems like the best way to go is simple sql.
def localized_children
   Category.find_by_sql(["
     SELECT DISTINCT c.id, c.parent_id, cl.name
     FROM categories AS c JOIN category_languages AS cl ON c.id = cl.category_id
     WHERE c.display = ? AND c.parent_id = ? AND cl.locale = ?
     ORDER BY c.sort_id ASC",
     true, self.id, I18n.locale])
end
Which results in one clean sql
SELECT DISTINCT c.id, c.parent_id, cl.name
FROM categories AS c JOIN category_languages AS cl ON c.id = cl.category_id
WHERE c.display = 1 AND c.parent_id = 307 AND cl.locale = 'en'
ORDER BY c.sort_id ASC
But in the view Use <%= @product.name %> instead of <%= @product.t.name %>

2010/02/04

has_many association でソート順を指定

モデルのなかで
has_many :children, :order => "sort ASC"
その他、ソートに便利な・・・
for child in @parent.children.reverse
# ...
end

2010/02/01

activerecord エラーを追加する方法

  def before_update
    if !check_something?
      self.errors.add(:name, "There's an error with the name")
      self.errors.add_to_base("There's an error with the name")
      return false
    end    
    return true
  end

2010/01/27

include と include で select を使う方法

Invoice(請求書) というテーブルに customer (顧客)が紐づいている場合、たいてい請求書と一緒に顧客名も表示する必要があります。
<% for invoice in @invoices %>
  <%= invoice.price %> <%= invoice.customer.name %>
<% end %>
のように。でも、この場合、invoice の数 + 1 のsql 文が発生するので無駄が多い。
そんなときは、関連テーブルも include するべし。
@invoices = Invoice.find(:all, :conditions => {..}, :include => :customer)
さらに、include したテーブルの一部しか使わない場合、:select も使いたいが、なぜか標準では、:inlcude したテーブルに :select が使えない。
@invoices = Invoice.find(:all, :conditions => {..}, :include => :customer, :select => 'customers.name, customer.id')
なんてできるといいのに。。。

これを可能にする pluging が Snow Giraffe の Eager loading select plugin. Rails 2.3 まで対応。

2010/01/11

Activerecord エラーメッセージの国際化

Activerecord で表示されるエラーメッセージを翻訳したいこともある。 そんな場合、デフォルトでは activerecord.errors のスコープを使う
ja:
  activerecord:
    models:
      memo: メモ
    errors:
      models:
        memo:
          attributes:
            content:
             blank: 空っぽさ