使用find_or_create_by时,关联id = nil

时间:2012-04-25 21:53:19

标签: ruby ruby-on-rails-3 associations

当我尝试通过find_or_create_by方法添加客户端时,我不会将trainer_id作为值传入(operator_id for client = nil)

即使你在我的Client_Controller中,我也有构建方法,我认为它会从current_trainer中提取id

我假设find_or_create_by_name和amp;之间存在脱节。构建方法。

非常感谢任何帮助。

Client_Controller

 def create
    @client = current_trainer.clients.build(params[:client])

    respond_to do |format|
      if @client.save
        ClientMailer.registration_confirmation(@client).deliver
        format.html { redirect_to @client, :notice => 'Client was successfully added.' }
        format.json { render :json => @client, :status => :created, :location => @client }
      else
        format.html { render :action => "new" }
        format.json { render :json => @client.errors, :status => :unprocessable_entity }
      end
    end
  end

锻炼模型

class Workout < ActiveRecord::Base

    belongs_to :client
    belongs_to :trainer

    validates_presence_of   :day, 
                            :client_id, 
                            :trainer_id, 
                            :message => "You have to indicated for when you want to schedule this workout."
    def client_name
        client.try(:name)
    end

    def client_name=(name)
        self.client = Client.find_or_create_by_name(name) if name.present?
    end

end

客户端模型

class Client < ActiveRecord::Base

    belongs_to :trainer

    before_save :generate_password

    has_many :workouts
    has_many :weigh_ins

    validates_presence_of   :name, :message => "You have to provide a client name in order to add new client."

    has_attached_file :profile_pic, :styles => { :micro => "60x60>", :small => "150x150>" }, 
                                    :default_url => 'profile_default_small.jpg',
                                    :storage => :s3,
                                    :s3_credentials => S3_CREDENTIALS,
                                    :bucket => '#',
                                    :path => ":attachment/:id/:style/:basename.:extension"

    validates_attachment_size   :profile_pic, 
                                :less_than => 3.megabytes,  
                                :message => "Your profile picture can`t be bigger than 3MB, sorry."

    def generate_password
        self.password = name[0..2].to_s + rand(99).to_s
    end

    def self.authenticate(email, password)  
        client = find_by_email(email)  
        if client && client.password == client.password
          client  
        else  
          nil  
        end
    end

服务器日志

  Started POST "/workouts" for 127.0.0.1 at Wed Apr 25 17:39:37 -0400 2012
    Processing by WorkoutsController#create as HTML
      Parameters: {"commit"=>"Schedule Session", "authenticity_token"=>"CxJSVfn0fwerdyrpA9/JEe8fX8Ep2/ZhnOqQkjZ3iwE=", "utf8"=>"✓", "workout"=>{"client_name"=>"John Doe", "day(1i)"=>"2012", "day(2i)"=>"4", "day(3i)"=>"29", "day(4i)"=>"21", "day(5i)"=>"00", "note"=>"", "title"=>"Current_Client"}}
      Trainer Load (0.1ms)  SELECT "trainers".* FROM "trainers" WHERE "trainers"."id" = ? LIMIT 1  [["id", 37]]
      Client Load (0.2ms)  SELECT "clients".* FROM "clients" WHERE "clients"."name" = 'John Doe' LIMIT 1
       (0.0ms)  begin transaction
      SQL (0.4ms)  INSERT INTO "clients" ("created_at", "email", "goal_weight", "name", "notes", "password", "profile_pic_content_type", "profile_pic_file_name", "profile_pic_file_size", "profile_pic_updated_at", "start_weight", "trainer_id", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["created_at", Wed, 25 Apr 2012 21:39:37 UTC +00:00], ["email", nil], ["goal_weight", nil], ["name", "John Doe"], ["notes", nil], ["password", "Joh55"], ["profile_pic_content_type", nil], ["profile_pic_file_name", nil], ["profile_pic_file_size", nil], ["profile_pic_updated_at", nil], ["start_weight", nil], ["trainer_id", nil], ["updated_at", Wed, 25 Apr 2012 21:39:37 UTC +00:00]]
    [paperclip] Saving attachments.
       (2.3ms)  commit transaction
       (0.1ms)  begin transaction
      SQL (0.5ms)  INSERT INTO "workouts" ("client_id", "created_at", "day", "note", "title", "trainer_id", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["client_id", 53], ["created_at", Wed, 25 Apr 2012 21:39:37 UTC +00:00], ["day", Sun, 29 Apr 2012 21:00:00 UTC +00:00], ["note", ""], ["title", "Current_Client"], ["trainer_id", 37], ["updated_at", Wed, 25 Apr 2012 21:39:37 UTC +00:00]]
       (1.1ms)  commit transaction
    Redirected to http://localhost:3000/workouts/64
    Completed 302 Found in 13ms (ActiveRecord: 4.8ms)

1 个答案:

答案 0 :(得分:1)

据我了解,find_or_create_by将使用create方法,而不是您的创建控制器操作。这就是为什么没有其他信息进入新的Client记录。

您可以将其他参数传递给find_or_create_by_name。如果找到记录,这些参数将被1)忽略;或者如果没有找到记录,则在create方法中使用这些参数。您需要为关系传递create其他参数,因为它不会像build那样自动处理它们。

你想要这样的东西:find_or_create_by_name(:name => name, :trainer_id => self.trainer_id)。请注意,使用其他参数时,需要将它们全部作为哈希传递。

更多信息:Passing extra data to find_or_create