For the information .*js.erb
is loaded when respective controller action take place.
I know the different version of this question is asked, so anyone having ability to flag this as duplicate will be quick to do it. I won't have any problem with that as long as I get the answer to my specific problem.
Problem is a s follows:-
When user is being is created/updated it goes through four action in controller, for creation new and create(if validation fails same partial is rendered with error message coming from create action) and to update edit and update, which have different partial serving the purpose. Although, ideally one partial should be enough but requirement differ for new and edit so... two, and keeping one will require lot of conditional statement ultimately leading it unreadability of code. Now, I have .*.erb.js file which is same for both the partials, and is required only when these page is requested. This leads to redundancy in code which is not good for maintainability of code moreover would like avoid putting js code in html file. For these two reasons, I would prefer a better solution to my problem. To state my trouble in exact sense I have listed couple of examples below:
@user
, is initialized in respective action of controller and phone_number_home and phone_number_general of user is validated. so in js.erb I have
<% if(@user.phone_number_home.present? || @user.phone_number_general.present?) %>
<%= do sth %>
<% else %>
<%= do sth %>
<% end %>
or something like:-
<% if(params[:action].to_s == "edit")%>
<%= do sth %>
<% else %>
<%= do sth %>
<% end %>
error report- in former says undefined method *phone_number_home* for nil:NilClass
and in latter it is undefined local variable or method
params'`, whereas same piece of code under script tag in views of _form_new.html.erb will work just ok. But not when it is kept in asset pipeline(which was the first trouble I faced while seeking my answer and after a lot googling this link sorted the problem out but only partially and ramifying my trouble into above one, so once again lot of googling got me multiple reference for solution, such as
1:) NoMethodError thrown when trying to use controller variables in js.erb file
2:) Even went over this screen-cast over and over again in case missed something
but none of them serve the purpose, besides above problem is just an example of what I should be able to do in with embedded javascript, to accentuate my problem I am also rendering a partial onClick()
of html tag, where I send different initialized variable in controller action so all these trouble for seeking an answer to my problem despite having workaround( put the code in respective partial _.*.html.erb
) to my trouble but to escape redundancy and strengthen maintainability of code, I need a better solution to my problem here.
Thanks in advance.