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

Ruby on rails 如何使用RubyonRails将数据从控制器传递到模型?,ruby-on-rails,ruby,ruby-on-rails-3,model-view-controller,model,Ruby On Rails,Ruby,Ruby On Rails 3,Model View Controller,Model,如何将数据从控制器传递到模型 在我的应用程序\u控制器中,我获取用户的位置(州和城市),并在\u过滤器之前包含一个,以便通过 before_filter :community def community @city = request.location.city @state = request.location.state @community = @city+@state end 然后,我尝试通过以下方式将控制器中检索到的数据添加到模型: before_sav

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

在我的
应用程序\u控制器
中,我获取用户的位置(州和城市),并在\u过滤器之前包含一个
,以便通过

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.city
request.location.state
在模型中不起作用。我知道其他一切都在起作用,因为如果我在
def_community
下将
@city
@state
定义为字符串,那么一切都在起作用,除了我没有动态变量,只是模型中放置了一个字符串。另外,我知道请求在控制器/视图中工作,因为我可以让它们显示正确的动态信息。问题只是将数据从控制器获取到模型。非常感谢您抽出时间。

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

因此,在Rails应用程序中,视图和控制器可以访问
请求
对象,而模型则不能。如果您想将当前请求中的信息传递给您的模型,则由您的控制器来完成。我将您的
添加社区
定义如下:

class用户
然后在控制器中:

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
class UsersController
我不希望直接传递
请求
对象,因为这实际上保持了模型与当前请求的分离。
用户
模型不需要了解
请求
对象或它们如何工作。它只知道它得到了一个
城市
和一个


希望有帮助

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

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

使用功能参数

# 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 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
模型中的
#
类用户

我建议您删除这个问题或其他问题,因为它们本质上是相同的。下次,如果你想让事情变得更清楚,你可以编辑你原来的问题:欢迎来到StackOverflow!记住对所有你认为有用的答案进行投票,包括对他人问题的答案。“检查”(选择)您的问题的最佳答案。@Laser很高兴听到:)编码愉快!