Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2572

association create & build not setting association at create time.

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.0.14
    • Affects Version/s: None
    • Component/s: None
    • None

      I'm not sure if this is somehow related to MONGOID-2218, but I'm trying to initialise a field's default value from an associated object, which is throwing a NoMethodError.

      I have something like the following:

      class User
        include Mongoid::Document
        has_many :blogs
        field :name
      end
      
      class Blog
        include Mongoid::Document
        belongs_to :user
        field :name, default: -> { "#{user.name}'s Blog" }
      end
      

      When I attempt to build or create a new blog via the user association:

      [Development]>> user = User.create name: 'Ralph Hinkley'
      [Development]>> user.blogs.create
      NameError: undefined local variable or method `user' for #<Blog:0x007fa6de436548>
      	from /Users/jnh/.rvm/gems/ruby-1.9.3-p327/gems/mongoid-3.0.13/lib/mongoid/attributes.rb:225:in `method_missing'
      	from /Users/jnh/Dev/tmp/blog_test/app/models/blog.rb:4:in `block in <class:Blog>'
      

      However, creating it and passing in the associated user object works, ie:

      [Development]>> Blog.create(user: user)
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            jamesotron James Harton
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: