且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 18:04:52

您正在纠结的概念是 MVC架构,就是职责分离.模型应该处理与数据库(或其他后端)的交互,而无需了解它们正在使用的上下文(无论是 HTTP 请求还是其他),视图不应该需要了解后端和控制器处理两者之间的交互.

The concept you're wrestling with is MVC architecture, which is about separating responsibilities. The models should handle interaction with the DB (or other backend) without needing any knowledge of the context they're being used in (whether it be a an HTTP request or otherwise), views should not need to know about the backend, and controllers handle interactions between the two.

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

So in the case of your Rails app, the views and controllers have access to the request object, while your models do not. If you want to pass information from the current request to your model, it's up to your controller to do so. I would define your add_community as follows:

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.

I prefer not to pass the request object directly, because that really maintains the separation of the model from the current request. The User model doesn't need to know about request objects or how they work. All it knows is it's getting a city and a state.

希望有所帮助.