简体   繁体   English

我应该在哪里创建在我的视图中使用的方法?

[英]Where should I create methods to use in my view?

Sorry for the newbie question, but I often wonder. 抱歉新手问题,但我常常想知道。 Where should I create methods that I want to use in my View?? 我应该在哪里创建我想在我的视图中使用的方法?

I'll illustrate. 我会说明一下。 I want to call a method in my user/views/show.html.erb that will return a boolean and with that I can show a link on the show page, or not. 我想在我的user / views / show.html.erb中调用一个方法,该方法将返回一个布尔值,并且我可以在显示页面上显示链接。

Well, I'll always thought that this method should be created at the User.rb, the model! 好吧,我一直以为应该在User.rb模型中创建这个方法! But what I actually get is an undefined method error! 但实际上我得到的是一个未定义的方法错误!

I would apreciate the help! 我会帮助你!

Thanks 谢谢

UPDATE UPDATE

It does work when I create the method in the User Helper .. But is that good programming? 当我在User Helper中创建方法时,它确实有效..但这是一个很好的编程吗? Is it the right way? 这是正确的方法吗? Or is there a better way? 还是有更好的方法吗?

Nowadays I prefer to use a presenter, similar to what is shown in this Railscast . 现在我更喜欢使用一个演示者,类似于这个Railscast中显示的 It keeps your code clean, reusable, and is more close to OO than Rails Helpers, which keeps you more sane. 它使您的代码保持清洁,可重用,并且比Rails助手更接近OO,这可以让您更加清醒。 :) :)

I think that if its display-related code, it should probably go into the specific helper, or in 'application_helper' if you want it available in all views. 我认为如果它与显示相关的代码,它可能应该进入特定的帮助程序,或者如果你希望它在所有视图中都可用,则应该在'application_helper'中。 Formatting and display logic (like what you have) should go into helpers. 格式化和显示逻辑(就像你拥有的那样)应该进入帮手。

If the method is going to make changes to your data, then it probably should go into a model. 如果该方法将对您的数据进行更改,那么它可能应该进入模型。 Not sure what you are getting an undefined method error, because it should work. 不确定你得到一个未定义的方法错误,因为它应该工作。

Actually guys, it's pretty simple The newbie here didn't call its user method using the object: example: @user.my_metho I was just calling my_method 实际上伙计,这很简单这里的新手没有使用对象调用其用户方法:例如:@ user.my_metho我只是调用my_method

That was the problem. 那就是问题所在。

But as Pedro mentioned the Draper gem really didn't do much for me... Couldn't even get it to work properly... 但正如佩德罗提到的那样,德雷珀宝石对我来说真的没什么用呢......甚至无法让它正常工作......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM