英文:
undefined method `render' for module in rails
问题
module UserCheck
def self.status(onboarding, params)
if onboarding && params[:process].present?
render json: { status: :ok }
else
render json: { error: 'You have already finished your onboarding.' }, status: :not_implemented
end
end
end
module MyAccount::User
class UserController < MyAccountController
def update
UserCheck.status(wizard_onboarding, params)
end
end
end
在users_controller
中,我使用UserCheck
模块来检查入职状态,并在else情况下返回错误。但是当else条件运行时,它不会呈现JSON错误消息,而是返回undefined method 'render' for UserCheck:Module
。你可以帮我解决这个问题吗?
英文:
module UserCheck
def self.status(onboarding, params)
if onboarding && params[:process].present?
render json: { status: :ok }
else
render json: { error: 'You have already finished your onboarding.' }, status: :not_implemented
end
end
end
module MyAccount::User
class UserController < MyAccountController
def update
UserCheck.status(wizard_onboarding, params)
end
end
end
In the users_controller, I am using the module UserCheck to check the onboarding status and return an error in the else case. But when the else condition runs it doesn’t render json error message but instead returns the undefined method 'render' for UserCheck:Module
. Could you help me fix this issue?
答案1
得分: 2
以下是您要翻译的内容:
我会将控制权传递给该方法,然后在该控制器上调用 render,就像这样:
module UserCheck
def self.status(onboarding, params, controller)
if onboarding && params[:process].present?
controller.render json: { status: :ok }
else
controller.render json: { error: '您已完成您的入职流程。' }, status: :not_implemented
end
end
end
module MyAccount::User
class UserController < MyAccountController
def update
UserCheck.status(wizard_onboarding, params, self)
end
end
end
就个人而言,我认为将如此简单的代码从控制器中提取到模块中没有任何好处。这使得控制器更难理解和调试。要理解控制器返回了什么,您需要查看不同的文件。
英文:
I would pass the controller to that method and call then render on that controller, like this:
module UserCheck
def self.status(onboarding, params, controller)
if onboarding && params[:process].present?
controller.render json: { status: :ok }
else
controller.render json: { error: 'You have already finished your onboarding.' }, status: :not_implemented
end
end
end
module MyAccount::User
class UserController < MyAccountController
def update
UserCheck.status(wizard_onboarding, params, self)
end
end
end
Personally, I see no benefit in extracting such simple code from the controller into a module. It makes the controller much harder to understand and to debug. And to understand what the controller is returning, you need to look into a different file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论