Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

many-tomany creates foreign key attributes

#4338

Hello,

Use rails 2.3.x

I this a feature or a bug ?

 class Word
   has_and_belongs_to_many :sentences
 end

 class Sentence
   has_and_belongs_to_many :words
 end

 sentenza = Sentence.first
 first_word = sentenza.words.first

 first_word.attributes #=> {"label"=>"This", "created_at"=>Wed Apr 07 15:48:30 UTC 2010, "updated_at"=>Wed Apr 07 15:48:30 UTC 2010, "sentence_id"=>"1", "id"=>1, "word_id"=>"1"}

I just want to try to make a deep copy of an ActiveRecord::Base object but I can't use attributes method :

Here is my example :

 words_attributes = sentenza.words.map(&:attributes)

 new_sentenza = Sentenza.create(:label => "2nd Sentence")

 new_sentenza.words.create(words_attributes) but it will fail (since word_id and sentence_id are not present in Word.column_names

Using a safe_attributes method will solve this issue but I am wondering if there is a better way to do it :

def safe_attributes
  attributes.select{|a| self.class.columns_hash[a] }
end

And the call:

 words_attributes = sentenza.words.map(&:safe_attributes)

Reported by Hery · April 7th, 2010 @ 05:08 PM

State: stale
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Santiago Pastorino
    Santiago Pastorino
    • State changed from new to open

    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 core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.

    Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.

    February 2nd, 2011 @ 04:44 PM

  2. Santiago Pastorino
    Santiago Pastorino
    • State changed from open to stale

    February 2nd, 2011 @ 04:44 PM