How do you pass data from a controller to a model with Ruby on Rails?

前端 未结 2 1138
南笙
南笙 2020-12-09 06:26

How do you pass data from a controller to a model?

In my application_controller I grab the user\'s location (state and city) and include a before_

2条回答
  •  情话喂你
    2020-12-09 06:49

    The class instance variables (those that start with @) in the controllers are separate from those in the models. This is the Model vs the Controller in MVC architecture. The Model and Controller (and view) are separated.

    You move info from a controller to a model explicitly. In Rails and other object oriented systems, you have several options:

    Use function parameters

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

    Docs

    Use instance variables attribute setters

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

    Passing data to models when the data is not 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
    

    Docs

提交回复
热议问题