如何使用Ruby on Rails将数据从控制器传递到模型?

如何将数据从控制器传递到模型?

在我的application_controller我获取用户的位置(州和城市)并包含一个before_filter ,以便通过所有控制器访问它

 before_filter :community def community @city = request.location.city @state = request.location.state @community = @city+@state end 

然后我尝试通过以下方法将控制器中检索到的数据添加到模型中:

 before_save :add_community def add_community self.community = @community end 

但是,数据从未从控制器传递到模型。 如果我使用:

 def add_community @city = request.location.city @state = request.location.state @community = @city+@state self.community = @community end 

request.location.cityrequest.location.state方法不能从模型中运行。 我知道其他一切都有效,因为如果我将@city@state定义为字符串,在def_community下,那么一切正常,除了我没有动态变量,只是放在模型中的字符串。 此外,我知道请求在控制器/视图中工作,因为我可以让它们显示正确的动态信息。 问题只是将数据从控制器传递到模型。 非常感谢你的时间。

您正在努力解决的概念是MVC架构 ,它涉及分离职责。 模型应该处理与DB(或其他后端)的交互,而无需了解它们正在使用的上下文(无论是HTTP请求还是其他),视图不需要知道后端,以及控制器处理两者之间的相互作用。

因此,对于Rails应用程序,视图和控制器可以访问request对象,而模型则不能访问。 如果要将当前请求中的信息传递给模型,则由控制器执行此操作。 我会按如下方式定义你的add_community

 class User < ActiveRecord::Base def add_community(city, state) self.community = city.to_s + state.to_s # to_s just in case you got nils end end 

然后在你的控制器中:

 class UsersController < ApplicationController def create # I'm assuming it's create you're dealing with ... @user.add_community(request.location.city, request.location.state) ... end end 

我不想直接传递request对象,因为这确实保持了模型与当前请求的分离。 User模型不需要知道request对象或它们的工作方式。 它所知道的是它正在建立一个city和一个state

希望有所帮助。

控制器中的类实例变量(以@开头的变量)与模型中的变量分开。 这是MVC架构中的模型与控制器。 模型和控制器(和视图)是分开的。

您可以显式地将信息从控制器移动到模型。 在Rails和其他面向对象的系统中,您有以下几种选择:

使用function参数

 # In the controller user = User.new(:community => @community) # In this example, :community is a database field/column of the # User model 

文件

使用实例变量属性设置器

 # In the controller user = User.new user.community = @community # same as above, :community is a database field 

当数据不是数据库字段时,将数据传递给模型

 # In the model class User < ActiveRecord::Base attr_accessor :community # In this example, :community is NOT a database attribute of the # User model. It is an instance variable that can be used # by the model's calculations. It is not automatically stored in the db # In the controller -- Note, same as above -- the controller # doesn't know if the field is a database attribute or not. # (This is a good thing) user = User.new user.community = @community 

文件