我在控制器上使用了会话变量 session [:parent] ,我想将这些变量传递给模型。如何将控制器中的参数传递给模型?
这是我的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 :(得分:0)
模型是数据库的接口。它们可以在没有会话的情况下使用(例如来自IRB)。允许模型与会话进行通信将违反MVC。因此会话对象在模型中不可见。将它作为参数传递给模型中的方法,或者在模型中定义一个返回所需内容的方法,然后将其存储在会话中(来自控制器)。
例如
class User < ActiveRecord::Base
def item_status
return :no_such_item
end
end
在您的控制器中
session[:item_status] = current_user.item_status
我希望它能让你清楚......