has_many_through_has_one.build does not set the foreign key #12698

bughit opened this Issue Oct 30, 2013 · 10 comments


None yet

7 participants



also applies to other initialize methods (find_or_initialize_by)


same in 4-0-stable and master

is this supposed to work?


@robin850 , @senny
Please take a look, to decide is it a bug. If it is, I will fix it.

Ruby on Rails member

I can confirm this on master.


Not 100% sure if this is supported, but putting the belongs_to :post_owner declaration on Post may help.

Ruby on Rails member

@al2o3cr adding that doesn't fix the issue.
Issue seems to be with how https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/association_scope.rb#L41-L103 is constructing a wrong where clause, which is getting neglected later down the chain.

@bughit bughit added the stale label Apr 23, 2014
Ruby on Rails member

This issue has been automatically marked as stale because it has not been commented on for at least
three months.

The resources of the Rails team are limited, and so we are asking for your help.

If you can still reproduce this error on the 4-1-stable, 4-0-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

@robin850 robin850 removed the stale label May 2, 2014
Ruby on Rails member

This is still a problem with 4.0.4, 4.1.0 and master according to the provided gist.


Thanks @robin850 , I've reproduced it too. I'll create patch for this.


I've created patch for this.

/cc @bughit @robin850 @rafaelfranca


As of right now, this does not work in Rails 4.1.5:

class Project < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships

class User < ActiveRecord::Base
  has_many :memberships
  has_many :projects, through: :memberships

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :project

class ProjectsController < ApplicationController
  def create
    @project = current_user.projects.build(project_params)
    if @project.save
      render json: @project, status: :ok
      render json: { errors: @project.errors }, status: :unprocessable_entity

  def project_params

The foreign keys are not set, I have to manually create the relationship by:

@project.users << current_user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment