Ruby on rails 关于在RubyonRails中使用模块的建议
我正在使用RubyonRails3,我知道在哪种情况下使用模块是好的 我有一个控制器,其中包括许多我以这种方式使用的私有方法:Ruby on rails 关于在RubyonRails中使用模块的建议,ruby-on-rails,ruby,ruby-on-rails-3,module,implementation,Ruby On Rails,Ruby,Ruby On Rails 3,Module,Implementation,我正在使用RubyonRails3,我知道在哪种情况下使用模块是好的 我有一个控制器,其中包括许多我以这种方式使用的私有方法: class UsersController < ApplicationController def update params[:option1] = get_user_option1 params[:option2] = get_user_option2 if params[:option2] params[:sav
class UsersController < ApplicationController
def update
params[:option1] = get_user_option1
params[:option2] = get_user_option2
if params[:option2]
params[:saving_success] = update_user
end
...
if params[:saving_success]
flash[:notice] = another_method_1
else
flash[:error] = another_method_2
end
end
private
def update_user
if params[:option1] == something
@user.save
end
end
def another_method_1
params[...] = ...
...
end
class UsersController
正如您所看到的,在私有方法中,我有类似ActiveRecords和params的方法。我知道在模块中不能直接使用那些ActiveRecords或params方法,但可以将它们作为参数传递,如本例所示:
# In the controller file
class UsersController < ApplicationController
include Users
def update
params[:option] = "true"
@users = Users.find(1)
Users::Validations.name (@user, params[:option])
...
end
end
# In the module file
module Users
module Validations
def Validations.name(user, param)
user == "Test_name" if param
# Normally the following is not possible:
# @user == "Test_name" if params[:option]
end
end
end
控制器文件中的#
类UsersController
那么,你对我的情况有什么建议?使用单独的模块好吗?
次要问题(目前…):
p.S.I:不要注意示例的简单性。写它们只是为了理解我在传递ActiveRecords和params方法时的两难处境
附言二:如果您需要其他信息,请告诉我。模块有两个主要用途:
但是,正如您猜对的,您不能使用params,您必须将其作为参数传递给模块的方法。关注点现在位于子目录
app/controllers/concerns
,app/models/concerns