简体   繁体   中英

Rails 4 - Helper Method - use in a view

I'm trying to figure out how to use helper methods in 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

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:

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.

Rails Helpers are modules which are included across your application. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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