我的应用程序的这一部分负责为拥有一个的连锁店(如 H&M)创建 Webshop 模型。如果该连锁店的网站也是网店,它会创建一个网店模型。
如果该网站不是网上商店,那么它就让它在链模型中的字符串。
问题:我正在使用复选框和虚拟属性执行此操作。因此,当向链控制器发送请求时,复选框会设置值“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
更新链模型时一切正常,但创建新模型时不行?我想不通为什么?
这是 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"=>"info@hm.com"}, "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" => "info@hm.com"}, "authenticity_token"=>"[HIDDEN]", "id"=>"444-h-m"}
有没有一种特殊的方法来处理 Rails 中新模型的 virtual_attributes?