タグ: RubyOnRails

rails の delegate で,移譲先のオブジェクトが nil になる場合の対応

December 14, 2013

delegate互いに関連を持つ User, Profile があるとして,ある User を主体として Profile#job を得るには user.profile.job とする必要があります.ですが,単に user.job とアクセスしたいと思うこともあるでしょう.class User < ActiveRecord::Base
belongs_to :profile def job profile.try(:job) end end
ということで, User#job メソッドを定義しました.しかし,この場合は,次のように移譲を用いることで解決することができます.class User < ActiveRecord::Base
belongs_to :profile delegate :job, to: :profile end

ActiveRecord の serialize を使う

December 11, 2013

ActiveRecord::Base .serializerails でオブジェクトをそのまま DB に保存したい場合, serialize が使える場合があります.class User < ActiveRecord::Base
serialize :group_ids end

simple_form で binary 型フィールドの file_field を使う

December 05, 2013

simple_formsimple_form は,煩雑になりがちなフォームの記述をシンプルにしてくれます.heartcombo/simple_form- form_for @user do |f|
%li name: = f.text_field :name %li email: = f.email_field :mail_address %li password: = f.password_field :password
通常,このように記述するところを,次のように書くことができます.- form_for @user do |f|
= f.input :name = f.input :mail_address = f.input :password
全部,input で済ませることができます.

rails でファイルをアップロードする際の挙動

December 04, 2013

経緯前回,画像ファイルをアップロードして DB に保存する記事を書きました.実際にファイルはどうやって DB に保存されるのかについて補足します.

rails で画像ファイルを DB に保存する

December 03, 2013

rails で画像を保存するrails 画像を扱うには,https://github.com/thoughtbot/papercliphttps://github.com/carrierwaveuploader/carrierwave といった便利な画像アップローダの gem がありますが,ちょっとしたアイコンやアバター,ロゴ,バナー画像などの類で,加工も必要ないような場合には DB にバイナリで突っ込んでおくくらいが手軽で良さそうです.

rake notes で,spec, js, coffee, scss, haml, slim のファイルも対象にする

December 06, 2011

Rails で rake note を打った時に、ruby のファイルしか検出してくれないので、js(coffee) や css(scss), html(slim, haml) も検出するようにした。

rails で Mix-in するときにすでにあるメソッドをオーバーライドする

May 23, 2011

module NewMethod
def self.included(mod) mod.class_eval do alias_method_chain :method, :new_method end end def method_with_new_method method_without_new_method 'new method' end end class Origin def method 'origin method' end include NewMethod end puts Origin.new.method #=> new method
include をメソッドの後に書かないといけないのが微妙