سؤال

لدي نموذج ، عندما يقوم بتثبيت كائن ، يقوم أيضًا بإنشاء كائن آخر مع نفس معرف المستخدم.

class Foo > ActiveRecord::Base

after_create: create_bar

private

def create_bar
  Bar.create(:user_id => user_id #and other attributes)
end

end

في bar.rb لديّ attr_protected لحمايته من المتسللين.

class Bar > ActiveRecord::Base
  attr_protected :user_id, :created_at, :updated_at
end

كما هو الحال الآن ، لا يمكنني إنشاء كائن شريط جديد دون تعطيل attr_protected أو الحصول على مستخدم كائن الشريط ، يذهب فارغًا ...

كيف يمكنني ترك كائن الشريط يقبل سمة: user_id من FOO دون فقد الحماية من ATTR_PROTCED؟

هل كانت مفيدة؟

المحلول

محاولة القيام:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end

نصائح أخرى

عند الاتصال new, create, ، أو find_or_create_by (وأي شخص آخر ينتهي به المطاف الاتصال new) يمكنك تمرير خيار إضافي ، without_protection: true.

http://api.rubyonrails.org/v3.2.22/classes/activerecord/base.html#method-c-new

attr_protected يقوم بتصفية السمات في attributes= الطريقة التي يتم استدعاؤها في new. يمكنك حل مشكلتك مع:

def create_bar
  returning Bar.new( other attributes ) do |bar|
    bar.user_id = user_id
    bar.save!
  end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top