我正在尝试销毁像这样的购买对象
def destroy
@purchase=current_user.purchases.where(flooding_property_id: params[:id])
@purchase.destroy(flooding_property_id: params[:id])
end
我知道这个错误是因为我有某种关联,但我似乎无法弄明白。我的模型如下
class FloodingProperty < ActiveRecord::Base
has_many :purchases
has_many :users, through: :purchases
end
购买模式
class Purchase < ActiveRecord::Base
belongs_to :user
belongs_to :flooding_property
end
用户模型
class User < ActiveRecord::Base
has_many :purchases
has_many :carts
has_many :flooding_properties, through: :purchases
end
数据库架构:
create_table "flooding_properties", force: :cascade do |t|
t.string "address"
t.string "zipcode"
t.geography "latlon", limit: {:srid=>4326, :type=>"point", :geographic=>true}
t.datetime "last_updated"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "flooding_properties", ["latlon"], name: "index_flooding_properties_on_latlon", using: :gist
add_index "flooding_properties", ["zipcode"], name: "index_flooding_properties_on_zipcode", using: :btree
create_table "purchases", force: :cascade do |t|
t.boolean "billed", default: false
t.integer "user_id"
t.integer "flooding_property_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "purchases", ["billed"], name: "index_purchases_on_billed", where: "(billed = false)", using: :btree
add_index "purchases", ["flooding_property_id"], name: "index_purchases_on_flooding_property_id", using: :btree
add_index "purchases", ["user_id"], name: "index_purchases_on_user_id", using: :btree
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
end
答案 0 :(得分:1)
您在单个实例上调用#destroy。这不是您的关联问题。
def destroy
current_user
.purchases
.find_by(flooding_property_id: params[:id])
.destroy
end
我使用.find_by而不是.where因为.where返回多个匹配。 .find_by总是返回它找到的第一个。
如果您确实要销毁所有匹配项,可以使用.where和.destroy_all:
def destroy
current_user
.purchases
.where(flooding_property_id: params[:id])
.destroy_all
end