rails勉強してます2
はまったりしながらだけど。
objectの情報をログにdump
# plain
logger.debug object.inspect
# yaml
logger.debug object.to_yaml
FKのnilを許可
belongs_to :tablename, optional: true
レコード削除時にリレーションテーブルも削除する
has_many :tablename, dependent: :destroy
リモートサーバにある画像ファイルをCarrierWaveで保存
mount_uploader :columnname, ExampleUploader
# カラム名がimage_urlとかだとremote_image_url_url になる
model.remote_columnname_url = "http://example.org/xxxx.png"
model.save
多対多のモデル表現
has_and_belongs_to_manyを使うと楽
中間テーブルの作成
class CreateGroupsUsers < ActiveRecord::Migration
def change
create_table :groups_users, id: false do |t|
t.references :group, index: true, null: false
t.references :user, index: true, null: false
end
end
end
中間テーブルのidはあってもなくても良い
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
中間テーブルへの登録は <<
演算子を使う
user = User.find( 1 )
group = Group.find(1)
user.groups << group