简体   繁体   English

Rails 4-辅助方法-在视图中使用

[英]Rails 4 - Helper Method - use in a view

I'm trying to figure out how to use helper methods in Rails 4. 我试图弄清楚如何在Rails 4中使用辅助方法。

I have two models, organisation and preferences. 我有两个模型,组织和偏好。

The associations are: 关联是:

Organisation has_one :preference
Preference belongs_to :organisation

In my preference table, I have an attribute called :prior_notice_required 在首选项表中,我有一个称为:prior_notice_required的属性

In my organisation view, I'm trying to display the organisation's preferences. 在我的组织视图中,我试图显示组织的首选项。 In my organisation view folder, I have a partial called preferences. 在我的组织视图文件夹中,我有一个部分称为首选项。

In my OrganisationsHelper.rb, I've tried this: 在我的OrganisationsHelper.rb中,我尝试了以下操作:

module OrganisationsHelper

    def publicity_notice_required
        if @organisation.preference.prior_notice_required == true
            'Prior notice of publicity is required'
        else
            'Prior notice of publicity is not required'
        end
    end

In my organisation preferences partial, I then try each of these: 在我的偏爱的组织中,然后尝试以下每种方法:

<%= @organisation.preference.prior_notice_required(publicity_notice_required) %>
<%= publicity_notice_required(@organisation.preference) %>

<%= publicity_notice_required(@organisation.preference.prior_notice_required) %>

I can't figure out how to get this working. 我不知道如何使它工作。 Does anyone have any experience with helpers to see where I'm going wrong? 有没有人与帮助者有任何经验,以了解我要去哪里错了?

It is as simple as calling <%= publicity_notice_required %> in the view. 就像在视图中调用<%= publicity_notice_required %>一样简单。

Rails Helpers are modules which are included across your application. Rails助手是应用程序中包含的模块。 This makes life easy but also has some drawbacks when it comes to Encapsulation & a good separation on concerns. 这使生活变得轻松,但是在封装和良好的关注点分离方面也存在一些缺点。

I'm not sure if this is right- but it seems to be working. 我不确定这是否正确-但似乎可行。

I change my view to: 我将观点更改为:

<%= publicity_notice_required(@organisation.preference) %>

and my helper to: 和我的助手:

def publicity_notice_required(organisation)
        if @organisation.preference.prior_notice_required == true
            'Prior notice of publicity is required'
        else
            'Prior notice of publicity is not required'
        end
    end

I'm not sure why the (organisation) needs to be in brackets or if its actually meant to include the preference as well. 我不确定为什么(组织)需要放在方括号中,或者实际上是否要包括偏好。 Hope this helps someone. 希望这对某人有帮助。

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

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