Can I get some help with my code here?

Hi,

Not sure if this is the appropriate place to put this but I asked a question on Stack Overflow and got a bit of interest but now my question seems to have been buried. Just wondering if I could get some help through here?

Here’s a link to my question: http://stackoverflow.com/questions/43229523/rails-why-is-my-parent-object-not-saving

So the items have a shopping_list_id attached but the shopping-list item itself won’t save for some reason.

Please let me know if there’s a more appropriate place to put this.

Thanks,

Jeff
:slight_smile:

Will reply here and if works repost to SO.

#1
As per suggested solution you need to change line

@shopping_list = ShoppingList.new(shopping_list_params)

to

@shopping_list = ShoppingList.create(shopping_list_params)

#2
Also, update the line

@shopping_list.items.build(name: ingredient.name, quantity: ingredient.quantity, unit: ingredient.unit, shopping_list_id: @shopping_list.id)

to (remove shopping_list_id param as it will be automatically set for you)

@shopping_list.items.build(name: ingredient.name, quantity: ingredient.quantity, unit: ingredient.unit)

If that doesn’t work maybe you could upload the project so it’s easier to debug

Ahh, thank you! - I will try this out tonight.

Hi Anton,

Unfortunately it didn’t work, when I use create instead of new, the same error gets hung up there as opposed to in the ‘respond_to’ block.

I really don’t get why the shopping_list controller is taking issue with the shopping_list_id. Wouldn’t its id parameter name just be, id instead of shopping_list_id? My items table does have a shopping_list_id column name, would that have anything to do with it?

Here’s a link to the repo if you want to have a look!

I’ve edited the shopping_lists controller to reflect the above changes.

Thanks,

Jeff

The issue is that Meal model has belongs_to :shopping_list but it doesn’t have column shopping_list_id.

So when you run

ShoppingList.create(meal_ids: ['1'])

Rails tries to create Meal model and link it back to the ShoppingList, but it can’t since there is no such attribute and error tells you that ActiveModel::MissingAttributeError. To fix create a migration e.g.:

add_column :meals, :shopping_list_id, :integer
2 Likes

Thank you very much @antulik, this worked!