2012-04-25 36 views
0

的時候,當我嘗試通過find_or_create_by方法我不`噸獲得trainer_id傳遞作爲增值客戶端(trainer_id客戶端=無)關聯ID =零使用find_or_create_by

即使你在我Client_Controller我有構建方法,我認爲會從current_trainer中拉出ID

我假設find_or_create_by_name &構建方法之間存在斷開。

希望對此有所幫助。

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) 
+0

你的Client類是什麼樣的?你在裏面使用'attr_protected'還是'attr_accessible'? – x1a4 2012-04-25 22:27:33

+0

此刻不使用任何屬性。 – 2012-04-25 22:30:40

回答

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

+0

我發現之前的某個地方,但是當我實現時,我得到一個錯誤:「被調用的id爲零,如果您真的想要nil的id,請使用object_id」。我知道@ current_trainer.id不是零。 – 2012-04-25 23:24:49

+0

如果您使用了'@ current_trainer',那麼它將無法工作,因爲您的鍛鍊模型中沒有'@ current_trainer'。您需要使用類似'self.trainer_id'的方式在鍛鍊模型中訪問它。我已經更新了我的答案以反映這一點。 – 2012-04-25 23:32:42

+0

感謝您的幫助。我設法找到一些竅門來克服這種不同(http://rails-bestpractices.com/posts/47-fetch-current-user-in-models) – 2012-04-26 00:12:33