Skip to content

Instantly share code, notes, and snippets.

@willnet
Created May 17, 2017 08:24
Show Gist options
  • Select an option

  • Save willnet/c6bfb94d79763b231eac1ccc4a2108ee to your computer and use it in GitHub Desktop.

Select an option

Save willnet/c6bfb94d79763b231eac1ccc4a2108ee to your computer and use it in GitHub Desktop.
inverse_of が必須なケース
class User < ApplicationRecord
has_one :post
end
class Post < ApplicationRecord
belongs_to :fuga, class_name: 'User'
end
u = User.new
post = u.build_post
post.valid? #=> false
post.errors #=> #<ActiveModel::Errors:0x007f9b5caf2400 @base=#<Post id: nil, user_id: nil, title: nil, body: nil, created_at: nil, updated_at: nil>, @messages={:fuga=>["must exist"]}, @details={:fuga=>[{:error=>:blank}]}>
post.fuga #=> nil
# 次のようにすると valid? が true になる
class User < ApplicationRecord
has_one :post, inverse_of: :fuga
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment