मैं दो मॉडल User
और Submission
बचाने:first_or_create ईमेल द्वारा और फिर इस रूप में नेस्टेड मॉडल
class User < ActiveRecord::Base
# Associations
has_many :submissions
accepts_nested_attributes_for :submissions
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :name, :role, :submission_ids, :quotation_ids, :submissions_attributes
validates :email, :presence => {:message => "Please enter a valid email address" }
validates :email, :uniqueness => { :case_sensitive => false }
end
class Submission < ActiveRecord::Base
belongs_to :user
attr_accessible :due_date, :text, :title, :word_count, :work_type, :rush, :user, :notes
validates :work_type, :title, :text,:presence => true
validates :text, :length => { :minimum => 250 }
validates :word_count, :numericality => { :only_integer => true }
end
मैं एक रूप है जो इन दो मॉडलों के लिए आवश्यक डेटा एकत्र करता है। उपयोगकर्ता नियंत्रक:
def index
@user = User.new
@user.submissions.build
end
def create
@user = User.where(:email => params[:user][:email]).first_or_create(params[:user])
if @user
redirect_to :root
else
render 'pages/index'
end
end
मैं क्या करना चाहता हूं सबसे पहले यह जांचें कि उपयोगकर्ता द्वारा सबमिट किए गए ईमेल द्वारा सिस्टम में पहले से मौजूद है या नहीं। यदि ऐसा है तो मैं उस उपयोगकर्ता के लिए एक सबमिशन बनाना चाहता हूं। अन्यथा एक ही समय में उपयोगकर्ता और सबमिशन बनाएं।
मैं first_or_create
विधि के साथ ऐसा करने के तरीके पर उलझन में हूं।
किसी भी मदद की सराहना की।
मुझे इसे निर्दिष्ट करने के बजाय 'विलय' करना चाहिए, लेकिन यह मेरी व्यक्तिगत वरीयता है। थोड़ा सा क्लीनर। –
धन्यवाद जो कि सबसे साफ उत्तर लगता है – chell
निर्माण केवल तभी कहा जाता है जब उपयोगकर्ता डेटाबेस में पहले से मौजूद नहीं है। मैंने पाया कि इससे कोई समस्या उत्पन्न हुई है क्योंकि जब उपयोगकर्ता पहले से मौजूद है तो यह सबमिशन ऑब्जेक्ट नहीं बनायेगा – chell