Rails 4 - Helper方法 - 在视图中使用

时间:2016-04-08 01:48:53

标签: ruby-on-rails associations helper

我试图弄清楚如何在Rails 4中使用辅助方法。

我有两种模式,组织和偏好。

协会是:

Organisation has_one :preference
Preference belongs_to :organisation

在我的偏好表中,我有一个名为:prior_notice_required

的属性

在我的组织视图中,我试图显示组织的偏好。在我的组织视图文件夹中,我有一个部分称为首选项。

在我的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

在我的组织偏好中,我会尝试以下各项:

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

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

我无法弄清楚如何让这个工作。有没有人有帮助的经验,看看我哪里出错了?

2 个答案:

答案 0 :(得分:1)

就像在视图中调用<%= publicity_notice_required %>一样简单。

Rails Helpers是整个应用程序中包含的模块。这使得生活变得简单,但在封装和封装方面也有一些缺点。关注问题的良好分离。

答案 1 :(得分:0)

我不确定这是否正确 - 但似乎有效。

我将观点改为:

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

和我的帮助:

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

我不确定为什么(组织)需要放在括号中,或者它实际上是否也包括偏好。希望这有助于某人。

相关问题