我有一個模擬房子的應用程序。房子has_many房間,房間has_many燈和small_appliances等,我也有一個名爲計算器控制器是如何訪問該應用程序。使用計算器控制器將數據添加到房屋(及其房間)。然後生成一個報告,位於app/views/calculator/report.html.erb。計算邏輯應該放到Rails應用程序中去哪裏?
我的問題是,報告的所有計算和邏輯都應該放在哪裏?目前我在視圖中都有,在calculator_helper中有一些東西。通常這會在模型中進行,對吧?但計算器沒有生成的模型。這是什麼標準?
這裏是計算器控制器。
class CalculatorController < ApplicationController
def index
end
def save_house
@house = House.new(params[:house])
respond_to do |format|
if @house.save
format.html { render :action => 'add_rooms', :id => @house }
format.xml { render :xml => @house, :status => :created, :location => @house }
else
format.html { render :action => 'index' }
format.xml { render :xml => @house.errors, :status => :unprocessable_entity }
end
end
end
def add_rooms
@house = House.find(params[:id])
@rooms = Room.find_by_house_id(@house.id)
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid house #{params[:id]}")
flash[:notice] = "You must create a house before adding rooms"
redirect_to :action => 'index'
end
def add_room
@room = Room.new(params[:room])
@house = @room.house
respond_to do |format|
if @room.save
flash[:notice] = "Room \"#{@room.name}\" was successfully added."
format.html { render :action => 'add_rooms' }
format.xml { render :xml => @room, :status => :created, :location => @room }
else
format.html { render :action => 'add_rooms' }
format.xml { render :xml => @room.errors, :status => :unprocessable_entity }
end
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid house #{params[:id]}")
flash[:notice] = "You must create a house before adding a room"
redirect_to :action => 'index'
end
def report
flash[:notice] = nil
@house = House.find(params[:id])
@rooms = Room.find_by_house_id(@house.id)
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid house #{params[:id]}")
flash[:notice] = "You must create a house before generating a report"
redirect_to :action => 'index'
end
end
請向我們展示您的計算器類。 – 2009-11-07 06:27:12
我喜歡James的回答。我想你應該問自己的另一個問題就是爲什麼你要突破常規 - 計算器控制器爲什麼要處理似乎屬於控制器的東西?我不是說你做錯了,我只是說這是值得多加思考的。 – 2009-11-07 08:38:21
好點,安迪。 Ryan,在你開始擔心控制器和視圖之前,先獲取MODELS。使用這種方法,您可能會發現所有計算的正確位置是House模型。 – 2009-11-07 16:11:14