Search code examples
ruby-on-railsmodelhas-manybelongs-to

Setting a 'has_many's object to carry it's parent id


I have an object called a tag which has_many :tweets. The tweet also has a corresponding belongs_to.

If I'm generating a tweet to save in the tag model like so:

        new_tweet = Tweet.new

        new_tweet.favorite_count = tweet.favorite_count 
        new_tweet.filter_level = tweet.filter_level 
        new_tweet.retweet_count = tweet.retweet_count 
        new_tweet.text = tweet.text 
        new_tweet.tweeted_at = tweet.created_at 

        new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z' 

        new_tweet.save 

How do I set that tweets parent to be the current tag? Would I do something like this?

new_tweet.tag = self

I tried this and it didn't work, whats a better solution? Thanks for your help.


Solution

  • Try create tweet's new object with association and tag_id will automatically assign in your new tweet object. So change Tweet.new to self.tweets.new and you are done.

    new_tweet = self.tweets.new
    
    new_tweet.favorite_count = tweet.favorite_count 
    new_tweet.filter_level = tweet.filter_level 
    new_tweet.retweet_count = tweet.retweet_count 
    new_tweet.text = tweet.text 
    new_tweet.tweeted_at = tweet.created_at 
    
    new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z' 
    
    new_tweet.save 
    

    As per your comment. You also have database structure issue. You need to resolve that first. You don't have tag_id in your tweets table assuming you take tag name column. To make my code work properly and create a proper parent child relation you must have parent_id in your child table.

    So try add tag_id in your tweets table and your error will gone. Also your value will save properly.