has_many_through_has_one.build does not set the foreign key #12698

Closed
bughit opened this Issue Oct 30, 2013 · 10 comments

Projects

None yet

7 participants

@bughit

https://gist.github.com/bughit/7228479

also applies to other initialize methods (find_or_initialize_by)

@bughit

same in 4-0-stable and master

is this supposed to work?

@iantropov

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

@vipulnsward
Ruby on Rails member

I can confirm this on master.

@al2o3cr

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

@vipulnsward
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
@rafaelfranca
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
@robin850
Ruby on Rails member

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

@iantropov

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

@iantropov

I've created patch for this.

/cc @bughit @robin850 @rafaelfranca

@DVG

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
end

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

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

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

  def project_params
    params.require(:project).permit(:name)
  end
end

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