Rails - 将控制器逻辑移动到模型中
我正在寻找清理我的控制器,因为它看起来又重又多余。任何有关我如何将这种类型的逻辑转移到我的模型中的帮助将不胜感激。感谢您对此的任何帮助 - 下面的代码是我的索引操作:
case params[:find_by]
when 'topic'
nuggets = Nugget.where(['topic = ?', params[:topic_name]])
@nuggets = nuggets.paginate(:page => params[:page],:per_page => 15)
@title = nuggets.first.topic
when 'audience'
nuggets = Nugget.where(['audience = ?', params[:audience_name]])
@nuggets = nuggets.paginate(:page => params[:page], :per_page => 15)
@title = nuggets.first.audience
else
@nuggets = Nugget.paginate(:page => params[:page], :per_page => 15)
end
I'm looking to clean up my controller, as it seems heavy and redundant. Any help on how I'd go about moving this type of logic into my model would be appreciated. Thanks for any help on this - the code below is my for index action:
case params[:find_by]
when 'topic'
nuggets = Nugget.where(['topic = ?', params[:topic_name]])
@nuggets = nuggets.paginate(:page => params[:page],:per_page => 15)
@title = nuggets.first.topic
when 'audience'
nuggets = Nugget.where(['audience = ?', params[:audience_name]])
@nuggets = nuggets.paginate(:page => params[:page], :per_page => 15)
@title = nuggets.first.audience
else
@nuggets = Nugget.paginate(:page => params[:page], :per_page => 15)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全确定我会将其移入模型中。我可能只是将其移至控制器中的私有实用程序方法中。
另一种选择是为不同的发现创建路线;不管值不值得,嗯。您可以将find_by逻辑移至模型中,或者使用
send
来稍微消除主题/受众差异,但同样,这似乎比其价值更麻烦。不过,我很想知道更多 Rails 爱好者对这个问题有何看法。
I'm not entirely sure I would move it into the model. I'd probably just move it into a private utility method in the controller.
Another option would be to create routes for the different finds; whether or not it's worth it, meh. You could move the find_by logic into the model, or use a
send
to slightly DRY up the topic/audience difference, but again, that seems more trouble than it's worth.I'll be interested to see what more Rails-y people think about the question, though.
将其添加到您的模型中
并在控制器中替换为此
您只需要对受众和主题使用相同的参数键
Add this to your model
And in the controller replace with this
You will just need to use same parameter key for audience and topic