2014-09-19 64 views
0

我用會話變量是會話[:父]控制器上,我想這些變量傳遞給建模。如何將控制器的參數傳遞給模型?如何從控制器訪問會話變量在Ruby中模擬on Rails的

這裏我controller.rb文件

def new 
    @child = Child.new 
    @child.pickup_people.build 
    @classes = [['Infant', 0], ['Toddlers', 1], ['Early learners', 2], ['Pre school', 3], ['Pre kindergarten', 4]] 
    @parent_types = [['Father', 'father'], ['Mother', 'mother'], ['Other', 'other']] 
    @martial_status = [['Married', 'married'], ['Single', 'single'], ['Divorced', 'divorced'], ['Separated', 'separated'], ['Widowed', 'widowed'], ['Other', 'other']] 
    @parent = Parent.new 

#parents those will be mapped with child, here mentioned to show in form page after creation 

if session[:parent_id] != nil 
    @parent_sessions = Parent.where(:id => session[:parent_id]) 
end 
end 

def create 
    logger.debug "\033[31mI am here\033[31m" 
    @child = Child.new(child_params) 
    if current_user.has_role? :day_care 
    @child.day_care_id = current_user.day_care.id 
    elsif current_user.has_role? :director 
    @child.day_care_id = current_user.director.day_care.id 
    elsif current_user.has_role? :assistant_director 
    @child.day_care_id = current_user.assistant_director.day_care.id 
    elsif current_user.has_role? :teacher 
    @child.day_care_id = current_user.teacher.day_care.id 
    end 
    respond_to do |format| 
    if @child.save 
    #  logger.debug "\033[31m#{session[:parent_id]}\033[31m" 
     if session[:parent] != nil 
     session[:parent].each do |p| 
      Relative.create(:child_id => @child.id, :parent_id => p["id"].to_i, :parent_type => p["type"]) 
     end 
     end 
    #### 
     gflash :success => "Child was succesfully created." 
     format.html { redirect_to @child } 
     format.json { render :show, status: :created, location: @child } 
     session[:parent] = nil 
     session[:parent_id] = nil 

     logger.debug "\033[31mdestroyed#{session[:parent_id]}\033[31m" 
    else 
     gflash :error => "Unable to create, please try again." 
     format.html { render :new } 
     format.json { render json: @child.errors, status: :unprocessable_entity } 
    end 
    end 
end 

感謝您的幫助!

+0

對不起,我不能告訴你的問題是什麼問題,我沒有看到有什麼不對,你試過了嗎? – martincarlin87 2014-09-19 13:00:33

+0

檢查http://stackoverflow.com/a/10237527/707636。可能你會得到一些想法。如果你能提供更多的細節,例如你想傳給模型的東西,它會很好。 – Bongs 2014-09-19 14:49:56

+0

感謝和我生病嘗試 – Karthick 2014-09-19 15:12:18

回答

0

模式是對數據庫的接口。它們可以在沒有會話的情況下使用(例如從IRB)。允許模型與會話交談會違反MVC。所以會話對象在模型中不可見。無論是把它作爲一個參數的方法在模型或定義模型中的一個方法,它返回你想要什麼,然後將其存儲在會話(從控制器)。

對於例如

class User < ActiveRecord::Base 
    def item_status 
    return :no_such_item 
    end 
end 

在你的控制器

session[:item_status] = current_user.item_status 

我希望它能讓你清楚......

相關問題