0

Guests purchase Items from other guests, so an Item will have a buyer and a seller, and a Guest will have Items purchased and Items bought.

class Guest < ActiveRecord::Base

  has_many :bought_items, class_name: 'Item', foreign_key: 'buyer_id'
  has_many :sold_items, class_name: 'Item', foreign_key: 'seller_id'

  accepts_nested_attributes_for :bought_items, :reject_if => lambda { |a| a[:price].blank? } , :allow_destroy => true
  accepts_nested_attributes_for :sold_items, :reject_if => lambda { |a| a[:price].blank? } , :allow_destroy => true
end

and

class Item < ActiveRecord::Base

  belongs_to :seller, class_name: 'Guest', foreign_key: 'seller_id', inverse_of: :bought_items
  belongs_to :buyer,  class_name: 'Guest', foreign_key: 'buyer_id', inverse_of: :sold_items

  attr_accessor :buyer_id, :seller_id

end

It appears the form is sending the POST data back correctly (I've only coded the purchases so far), for:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gR+GZfhT4CffM3ML9LkZaYK+eA85a1oLRG+NRqoRnY=",
 "guest"=>{
     "guest_number"=>"3",
     "bought_items_attributes"=>{
        "0"=>{
            "item_number"=>"432",
            "description"=>"test",
            "seller_id"=>"27",
            "sales_price"=>"10.0", "id"=>"1"},
        "1"=>{
            "item_number"=>"",
            "description"=>"",
            "seller_id"=>"27",
            "sales_price"=>"0.0"}
       }
  },
 "commit"=>"Save Changes",
 "id"=>"28"}

Updates happen for changing the guest_number, but not for any of the nested attributes. Is there something wrong in the model setup?

This is Rails 3.1.

2 Answers 2

1

Your reject_if block says to reject data if the price attribute is blank, which it is - your post data has sales_price instead.

You do also want to get rid of that attr_accessor as lucapette points out.

1
  • Oh my. That is indeed the problem. I have been looking at it for hours! Sigh... Thank you so much for your help.
    – Brenda
    Dec 22, 2011 at 18:06
0

The attr_accessor is a problem for sure. Maybe you would have used attr_accessible.

1
  • Thank you for your reply. I've tried and with and without the attr_accessor and the problem still occurs.
    – Brenda
    Dec 22, 2011 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.