0

当我尝试通过 find_or_create_by 方法添加客户端时,我没有将 trainer_id 作为值传入(客户端的 trainer_id = nil)

即使你在我的 Client_Controller 我也有 build 方法,我假设它会从 current_trainer 中提取 id

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

对此有任何帮助将不胜感激。

客户端控制器

 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)
4

1 回答 1

1

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

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

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

更多信息:将额外数据传递给 find_or_create

于 2012-04-25T22:45:49.520 回答