无法在轨道3.2.12中找到带有ID的模型

时间:2013-05-28 10:28:10

标签: ruby-on-rails associations

我有这个方法。我根本无法理解错误

Couldn't find Company without an ID
ActiveRecord::RecordNotFound in CustomersController#bulk_create

中的

编写此方法是为了批量创建公司客户,方法是使用name:number格式的名称和数字。

方法如下:

def bulk_create
res = ""
comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first
comp = Company.find(comp_id)
s = SentSmsMessage.new
s.set_defaults
s.data = tmpl("command_signup_ok", customer, comp) unless params[:customer][:email].length > 0
s.data = params[:customer][:email] if params[:customer][:email].length > 0
s.company = comp if !comp.nil?
s.save
unless comp_id.blank?
  params[:customer][:name].lines.each do |line|
    (name, phone) = line.split(/\t/) unless line.include?(":")
    (name, phone) = line.split(":") if line.include?(":")
    phone = phone.gsub("\"", "")
    phone = phone.strip if phone.strip.to_i > 0
    name = name.gsub("\"", "")
    name = name.gsub("+", "")
    phone = "47#{phone}" if params[:customer][:active].to_i == 1
    customer = Customer.first(:conditions => ["phone_number = ?", phone])
    if customer.nil?
      customer = Customer.new
      customer.name = name
      # customer.email
      # customer.login
      # customer.password
      customer.accepted_agreement = DateTime.now
      customer.phone_number = phone
      customer.active = true
      customer.accepted_agreement = DateTime.now
      customer.max_msg_week = params[:customer][:max_msg_week]
      customer.max_msg_day = params[:customer][:max_msg_day]
      customer.selected_companies = params[:customer][:selected_companies].delete_if{|a| a.blank?}
      res += "#{name} - #{phone}: Create OK<br />" if customer.save
      res += "#{name} - #{phone}: Create failed<br />" unless customer.save
    else
      params[:customer][:selected_companies].each do |cid|
        new_company = Company.find(cid) unless cid.blank?
        if !new_company.nil? 
          if !customer.companies.include?(new_company)
            customer.companies << new_company
            if customer.save
              res += "#{name} - #{phone}: Customer exists and the customer was added to the firm #{new_company.name}<br />"
            else
              res += "#{name} - #{phone}: Customer exist, but something went wrong during storage. Check if the client is in the firm.<br />" 
            end
          else
            res += "#{name} - #{phone}: Customer exists and is already on firm #{new_company.name}<br />"
          end
        end
      end
    end
    s.sms_recipients.create(:phone_number => customer.phone_number)
  end
  s.save
  s.send_as_sms
  @result = res
  respond_to do |format|
      format.html { render "bulk_create"}
  end
else
  @result = "You have not selected any firm to add these users. Press the back button and try again."
  respond_to do |format|
      format.html { render "bulk_create"}
  end
end
end

我想在这里更新一个情况。当我将表单提交为空白时,它会出现此错误。此外,如果我用表格填充表格,那么它会显示方法在失败的情况下返回的情况。

 res += "#{name} - #{phone}: Create failed <br />"

tmpl方法

private
def tmpl(setting_name, customer, company = nil)
text = ""
 if customer.companies.count > 0
   sn = "#{setting_name}_#{@customer.companies.first.company_category.suffix}".downcase rescue setting_name
   text = Setting.value_by(sn) rescue ""
 end
textlenth = text.length rescue 0
 if textlenth < 3
   text = Setting.value_by(setting_name) rescue Setting.value_by("command_error")
 end
 return fill_template(text, customer, company)
end

来自模型customer.rb

    def selected_companies=(cmps)
  cmps.delete("")
  # Check the old ones. Make a note if they are not in the list. If the existing ones are not in the new list, just remove them
  self.companies.each do |c|
    self.offer_subscriptions.find(:first, ["customer_id = ?", c]).destroy unless cmps.include? c.id.to_s
    cmps.delete c.id.to_s if cmps.include? c.id.to_s
    end

  # Then create the new ones
  cmps.each do |c2|
    cmp = Company.find(:first, ["id = ?", c2])
    if cmp && !c2.blank?
      offerSubs = offer_subscriptions.new
      offerSubs.company_id = c2
      offerSubs.save
    end
  end
end

    def selected_companies
       return self.companies.collect{|c| c.id}
    end

客户关联如下:

has_many :offer_subscriptions
has_many :companies, :through => :offer_subscriptions

此代码由其他人编写。我试图理解这种方法,但到目前为止还无法理解这段代码。 请帮忙。 提前谢谢。

4 个答案:

答案 0 :(得分:0)

您收到'找不到没有ID的公司'错误,因为您的公司表不包含id = comp_id的记录

comp = Company.find(comp_id)更改为comp = Company.find_by_id(comp_id)

这将返回nil而不是错误。

已在您的代码中处理添加comp is not nil条件。

答案 1 :(得分:0)

你的comp_id行返回零。

comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first

发布传递给此函数的参数,我们可以找到原因。在此期间,您可以将块封装在begin - rescue块中以捕获这些错误:

begin
  <all your code>
rescue ActiveRecord::RecordNotFound
  return 'Unable to find a matching record'
end

答案 2 :(得分:0)

试试这个:

  comp = ""
  comp = Company.find(comp_id)  unless comp_id.nil?

而不是comp = Company.find(comp_id)

进一步nil检查您的代码中的内容。

答案 3 :(得分:0)

Reason being

params[:customer][:selected_companies].delete_if{|a| a.blank?} = []
so [].first = nil
therefor, params[:customer][:selected_companies].delete_if{|a| a.blank?}.first = nil
and comp_id is nil



So check the log file and check what is coming in the parameter "selected_companies"

when you will find the parameter, everything will be understood well....