Railsの雑多なメモ(assign_attributes、バリデーションnumericality、render_to_string、delegate、truncate)
assign_attributes
特定のattributeを変更するためのメソッド。オブジェクトの変更をしただけで、DBには保存されない。
article.assign_attributes( article_params ) def article_params params.require(:article).permit( :title, :description, :state ) end
Active Recordのattributesの更新メソッド | 酒と涙とRubyとRailsと
ActiveRecord の attribute 更新方法まとめ - Qiita
バリデーションnumericality
属性に数値のみ(Numericクラス)が使われていることを検証するバリデーション。
class Player < ApplicationRecord validates :points, numericality: true end
数値の上限を制限するless_than_or_equal_to
オプションや、下限を制限するgreater_than_or_equal_to
オプションなど、オプション指定することで制約を追加できる。
class Player < ApplicationRecord # 100以下の数値になるように制限する validates :points, numericality: { less_than_or_equal_to: 100 } # 10以上の数値になるように制限する validates :points, numericality: { less_than_or_equal_to: 10 } # 以下のように複数オプションを指定することもできる validates :points, numericality: { less_than_or_equal_to: 100, greater_than_or_equal_to: 10 } end
render_to_string
コントローラーないで使用するメソッド。renderした結果のviewをブラウザで表示する必要がなく、文字列として取得する場合はrender_to_string
メソッドを使用する。
# render先のviewを文字列で返している controller.render_to_string("shared/_media_image", locals: { medium: medium }, layout: false) => "<div class=\"media-image\"><img src=\"http://localhost:3000/rails/active_storage/representations/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBRQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--dde48d8f52e682864a7f2b7d68a3468f7f1fa227/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdCam9MY21WemFYcGxTU0lOTVRBeU5IZzNOamdHT2daRlZBPT0iLCJleHAiOm51bGwsInB1ciI6InZhcmlhdGlvbiJ9fQ==--6ec66a681693b203f182cf67cd6ee51b8eb65eca/sample01.jpg\" /></div>"
delegate
アソシエーションを組んだモデルのメソッドを簡単に移譲できるようにするメソッド。
以下の記述をすることで、user.profile.name
を記述する所をuser.name
と記述することができる。
class User has_one :profile delegate :name, to: :profile end
prefixオプションをtrueにすると、生成されるメソッド名にプレフィックスを追加できる。今回の場合だとメソッド名がuser.profile_name
になる。
class User has_one :profile delegate :name, to: :profile, prefix: true, allow_nil: true end
Active Support コア拡張機能 - Railsガイド
truncate
文字列の最後を切り捨てて省略表示するメソッド。String#truncate
とTextHelper
としてのtruncateがある。
'Once upon a time in a world far far away'.truncate(27) # => "Once upon a time in a wo..."
truncate("Once upon a time in a world far far away", length: 20) # => "Once upon a time ..."