0
我的應用程序的這個特定部分需要創建一個存儲鏈(如H & M)的Webshop模型。如果連鎖店有一個也是網上商店的網站,它會創建一個網上商店模型。Rails中新模型的虛擬屬性?
如果該網站不是網上商店,那麼它可以讓它只是在鏈模型中的字符串。
問題:我正在做一個複選框和虛擬屬性。所以當向鏈控制器發送一個請求時,一個複選框設置值'set_webshop'。
# Chain Model
class Chain
has_one :webshop, :dependent => :destroy
def set_webshop
self.webshop.url == self.website unless self.webshop.blank?
end
def set_webshop=(value)
if self.webshop.blank?
value == "1" ? self.create_webshop(:url => self.website) : nil
else
value == "1" ? nil : self.webshop.destroy
end
end
end
# Chain Controller
class ChainsController < ApplicationController
def create
@chain = Chain.new(params[:chain])
respond_to do |format|
if @chain.save
flash[:notice] = 'Chain was successfully created.'
format.html { redirect_to(@chain) }
format.xml { render :xml => @chain, :status => :created, :location => @chain }
else
format.html { render :action => "new" }
format.xml { render :xml => @chain.errors, :status => :unprocessable_entity }
end
end
end
def update
params[:chain][:brand_ids] ||= []
@chain = Chain.find(params[:id])
respond_to do |format|
if @chain.update_attributes(params[:chain])
flash[:notice] = 'Chain was successfully updated.'
format.html { redirect_to(@chain) }
format.js
else
format.html { render :action => "edit" }
end
end
end
end
當更新Chain模型時,這一切都很完美,但是當創建一個新模型時,它完全可以正常工作嗎?我無法弄清楚爲什麼?
以下是POST和PUT請求。
# POST (Doesn't work - does not create a Webshop)
Processing ChainsController#create (for 127.0.0.1 at 2010-02-06 11:01:52) [POST]
Parameters: {"commit"=>"Create", "chain"=>{"name"=>"H&M", "set_webshop"=>"1", "website"=>"http://www.hm.com", "desc"=>"...", "email"=>"[email protected]"}, "authenticity_token"=>"[HIDDEN]"}
# PUT (Works - does create a Webshop)
Processing ChainsController#update (for 127.0.0.1 at 2010-02-06 11:09:13) [PUT]
Parameters: { "commit"=>"Update", "chain"=> { "name" => "H&M", "set_webshop"=>"1", "website" => "http://www.hm.com", "desc" => "...", "email" => "[email protected]"}, "authenticity_token"=>"[HIDDEN]", "id"=>"444-h-m"}
是否有一種特殊的方式來處理Rails中新模型的virtual_attributes?
謝謝,工作就像一個魅力! – 2010-02-06 14:15:41