我有一个表单,其中Application模型接受个人属性和Contact属性。联系人属性依次接受移动属性。我在第11行NoMethodError in ApplicationsController#create
获得了undefined method 'mobile' for #<Mobile:0x007fe7d5755318>
和if @application.save!
。
我的applications_controller.rb
如下:
class ApplicationsController < ApplicationController
def new
@application = Application.new
@application.build_personal
contact = @application.build_contact
2.times { contact.mobiles.build }
end
def create
@application = Application.new(application_params)
if @application.save!
flash[:success] = "Your application has been submitted successful"
redirect_to root_path #need to be changed
else
flash[:alert] = "Some error occured please try again"
render :new
end
end
def index
end
private
def application_params
params.require(:application).permit( personal_attributes: [:first_name, :last_name, :fathers_name, :mothers_name, :middle_name, :blood_group, :gender, :religion, :caste, :date_of_birth],
contact_attributes: [:phone, mobiles_attributes: [:id, :mobile_no]])
end
end
我的contact.rb
如下:
class Contact < ActiveRecord::Base
belongs_to :application
has_many :mobiles, dependent: :destroy
accepts_nested_attributes_for :mobiles, reject_if: lambda {|attributes| attributes['mobile_no'].blank?}
end
我的application.rb如下:
class Application < ActiveRecord::Base
has_one :personal, dependent: :destroy
has_one :contact, dependent: :destroy
accepts_nested_attributes_for :personal
accepts_nested_attributes_for :contact
before_save :generate_appid
private
def generate_appid
self.app_id = (Application.last.id+1)+1000
end
end
我的mobile.rb如下:
class Mobile < ActiveRecord::Base
belongs_to :contact
validates :mobile, presence: true, numericality: { only_integer: true }
end