我正在使用Rails 4.2版和ruby 2.2.0版。我正在尝试将记录保存到lollypops表。没有例外说明原因。

任务:创建并保存member后,我想通过在成员控制器的lollypops方法中调用create_lollypop(@member.id)来填充create表,如下所示:

 #   POST /members
 #   POST /members.json
  def create

 @member = Member.create(members_params)
   return unless request.post?

   @member.save!
   self.current_user = @member
   c = Country.find(@member.country_id)
   @member.update_attributes(
   :country_code=>c.code)
   create_lollypop(@member.id) #From here I want to create lollypop
   MemberMailer.signup_notification(@member).deliver_now

   redirect_to(:controller => '/admin/members', :action => 'show',
   :id=> @member.id)
   flash[:notice] = "Thanks for signing up! Check your email now to
   confirm that    your email is correct!"

   rescue ActiveRecord::RecordInvalid
   load_data
   render :action => 'new'

  end

def create_lollypop(member_id)
 @member = Member.find(member_id)
    Lollypop.create(
    :member_id=>@member.id,
    :product_name=>'lollypop',
    :product_price=>100,
    :email=>@member.email,
    :house_flat => @member.house_flat,
    :street=>@member.street,
    :city_town=>@member.city_town,
    :country =>@member.country,
    :postcode_index=>@member.postcode_index,
    :name=>@member.name)
end


创建了“成员”,但未填充“ lollypops”表。关联是:

成员模型:

 has_one :lollypop, :dependent=>:destroy


LOLLYPOP模型

  belongs_to :member


如果我使用通用SQL命令,则会填充lollypops表,但我不想这样做:

def self.create_lollypop(member_id)
   member = Member.find(member_id)
ActiveRecord::Base.connection.execute("insert into lollypops (member_id,product_name,product_price,email,house_flat,street,city_town,country,postcode_index,name)
   values(#{member.id},'lollypop',#{100},'#{member.email}','#{member.house_flat}','#{member.street}','#{member.city_town}','#{member.country_code}','#{member.postcode_index}','#{member.name}')")

end


任何建议都将受到欢迎。谢谢。

最佳答案

在您的create_lollypop()中,您未定义@member。

def create_lollypop(member_id)
  @member = Member.find member_id
  Lollypop.create!(
    :member_id=>@member.id,
    :product_name=>'lollypop',
    :product_price=>100,
    :email=>@member.email,
    :house_flat => @member.house_flat,
    :street=>@member.street,
    :city_town=>@member.city_town,
    :country =>@member.country,
    :postcode_index=>@member.postcode_index,
    :name=>@member.name
  )
end


也可以使用create!因此,如果任何验证失败,则将引发异常。因此,它将帮助您解决问题。

关于mysql - 无法在数据库中创建记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29984550/

10-08 21:54