I have three entities: user, contact & engagement. user that has_many: contacts. contact belongs_to: user. A user makes an engagement with a contact. I have also that an engagement belongs_to: contact.
In my views/contacts/show.html.erb I want to show a particular contact's page and let a user register an engagement with the contact by filling an engagement form. I want the engagement that is created on the contact's page to be associated with that particular contact.
So I show a contact:
resources :contacts
resources :engagements, only: [:create, :edit, :destroy]
class ContactsController < ApplicationController
include ApplicationHelper
def show
@contact = Contact.find(params[:id])
set_current_contact @contact.id #pass the particular id to helper
end
end
Define method in helper:
module ApplicationHelper
def set_current_contact(contact_id)
@current_contact = Contact.find_by(id: contact_id)
end
def the_current_contact
@current_contact #create instance variable for the other helper
end
end
The key thing I am trying to do is to make the engagements controller 'know' for which contact the user is registering an engagement. i.e. pass @contact to EngagementsController
class EngagementsController < ApplicationController
def create
@engagement = the_current_contact.engagements.build(engagement_params)
end
end
I get the error:
undefined method `set_current_contact' for #<EngagementsController:0x007f2c2c24f360>
First problem is that I do not understand why the controller can not access a method from the ApplicationHelper?
I did not mean to ask two somehow different questions but the second issue is whether using the helper in this way is the right approach. I understand that HTTP is a stateless protocol and in this case helpers become useful fort passing instance variables. I have searched for similar posts and found related Rails: Set a common instance variable across several controller actions but though it recommends helpers as the solution it does not explain in particular how to use the helper.
EDIT: I have added the missing include ApplicationHelper in the EngagementsController. Now the error is:
wrong number of arguments (given 0, expected 1)
Extracted source (around line #13):
end
13 def set_current_contact(contact_id)
14 @current_contact = Contact.find_by(id: contact_id)
15 end
include ApplicationHelperin your EngagementsController. And even when you fix this, you are correct in your assumption that it will not work as you expect :)