获取在控制器/视图中工作的方法在模型中运行,Ruby on Rails

我正在尝试根据用户的位置向位置列下的用户模型添加字符串。 我已经完成了所有设置,我知道@ city + @ state的值被添加到正确模型中的相应列中。 问题是,似乎request.location.city和request.location.state在控制器和视图中正常运行,但在模型中却没有。

def add_location @city = request.location.city @state = request.location.state @location = @city+@state self.location = @location end 

创建用户时,不会创建任何字符串,例如“losangelescalifornia”。 当我定义@city =“bob”和@state =“cat”时,所有创建的用户都在适当的位置有“bobcat”。 我知道除了这些基于地理定位的方法之外,一切都在运行。 所以我的问题是,如何在模型中运行这些方法(请纠正我,如果它不是它们),即request.location.city和request.location.state? 提前谢谢了 :)

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

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

 class User < ActiveRecord::Base def add_location(city, state) self.location = 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_location(request.location.city, request.location.state) ... end end 

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

希望有所帮助。

请求变量在模型中不可用,因为它取决于当前的HTTP请求。 你必须作为param传递给model。

 def your_action ... @model.add_location(request) ... end def add_location(request) .. end