Saving a collection field with <<


#1

I have habtm relationship between articles and contributors.
Everything’s working fine, except when I create a new article Rails
doesn’t seem to save the contributors that belong to it into
articles_contributors. This is the controller (that I pilfered from
typo):

def new
@article = Article.new(params[:article])
[…]
if request.post?
@article.contributors.clear
@article.contributors << Contributor.find(params[:contributors])
if params[:contributors]
if @article.save
[…]

This saves everything in the form, except the selected contributor(s).
What’s driving me crazy is that I’m using exactly the same in the edit
method and it works fine (the selected contributors get saved):

def edit
@article = Article.find(params[:id])
@article.attributes = params[:article]
[…]
if request.post?
@article.contributors.clear
@article.contributors << Contributor.find(params[:contributors])
if params[:contributors]
if @article.save
[…]

Typo, where I basically stole this method, from uses the same technique.
I don’t understand why it’s not saving when I create a new record, but
then works when I do an edit. The form is the same obviously, and I’ve
examined the param variables submitted and the contributors[] array is
there with the values in it. It’s just not getting << into
article.contributos or saved properly. I checked the models in typo to
see if there were any special overloads for this, but there don’t seem
to be.

I’m pulling my hair out with this problem, I know I must be missing
something stupid. Thanks in advance to anyone who can help.


#2

Damn word wrap. Those “if params[:contributors]” lines are actually at
the end of the lines above, not on a line by themselves.


#3

Chris Johanesen wrote:

  @article.contributors.clear
  @article.contributors << Contributor.find(params[:contributors]) 

if params[:contributors]
if @article.save
[…]

This saves everything in the form, except the selected contributor(s).
What’s driving me crazy is that I’m using exactly the same in the edit
method and it works fine (the selected contributors get saved):

This is a known bug in ActiveRecord in Rails 1.0. Either move
to Edge Rails or save @article before adding contributors.


We develop, watch us RoR, in numbers too big to ignore.