我正试图摧毁这样的购买对象
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发布于 2016-12-16 02:00:13
你在一个实例上调用# single。这不是你的协会的问题。
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
endhttps://stackoverflow.com/questions/41176138
复制相似问题