wrong number of arguments (given 0, expected 1) rails 6.1.1 - ruby-on-rails-6.1

I check current page with rails 5.1.2 and no problem, but rails 6.1.1 error wrong number of arguments (given 0, expected 1)
<% if current_page?(controller: 'categories', action: 'new')%>
<%= link_to "←".html_safe + #shop.name, shops_path, class: "btn btn-sm btn-primary" %>
<%else%>
<%= link_to "← Volver".html_safe, new_shop_category_path, class: "btn btn-sm btn-primary" %>
<%end%>
My first solution is
<% if controller_name == 'categories' && action_name == 'new'%>
but I would like to know the problem
any idea?
Thanks!

Related

Can you the coccon gem without a direct nested association?

I have to convert my form to not using nested association. In other words, instead of
<%= link_to_add_association f, :contacts, class: 'btn btn-primary', partial: 'projects/contact_fields', data: {
association_insertion_node: '.contact_fields', association_insertion_method: :append
} do %>
<i class="fas fa-plus"></i>
<% end %>
<%= f.fields_for :contacts do |contact| %>
<%= render 'projects/contact_fields', f: contact %>
<% end %>
I would like to be able to just pass in a string to be used as the container (similar to how you can with field_for).
<%= link_to_add_association 'contacts[]', 'projects/contact_fields', class: 'btn btn-primary', partial: 'projects/contact_fields', data: {
association_insertion_node: '.contact_fields', association_insertion_method: :append
} do %>
<i class="fas fa-plus"></i>
<% end %>
<% #contacts.each_with_index do |contact, index| %>
<%= fields_for "contacts[#{index}]", contact do |c| %>
<%= render 'projects/contact_fields', f: c %>
<% end %>
<% end %>
Cocoon is currently unable to edit/manage a collection. Cocoon is just helping the form-behaviour for nested-children functionality in rails, so there is no simple solution to edit an array or collection. On the other hand, this is in general pretty simple to implement without cocoon.
Very high level, do something like:
#contacts.each do |contact|
= render `contacts/edit`, contact: contact
= render `contacts/new`
so render the edit form for each existing contact, and render an empty new form. You will have to edit your controller functionality a little, because you will always re-render the complete collection/index page (with all existing contacts in the collection?).
So you can just render multiple forms on one page. Using turbolinks this will render fast and feel actually completely the same. You could use xhr to update only specific parts of the page, but to get started that is not even needed.
So I ended up following drifting ruby and using code from the cocoon gem to implement something myself. I hope others can benefit from it. Thank you nathanvda for the cocoon gem which helped me with the code below, really wish I could have used it:
add this to your app/helpers/application_helper.rb
def link_to_add_row(*args, &block)
if block_given?
link_to_add_row(capture(&block), *args)
else
#byebug
name, association, new_object, partial, html_options = *args
html_options ||= {}
html_options[:class] = [html_options[:class], "custom_add_fields"].compact.join(' ')
id = 'NEW_RECORD'
fields = fields_for("#{association}[#{id}]", new_object, child_index: id) do |builder|
#byebug
render( partial, f: builder)
end
fields = CGI.escapeHTML(fields).html_safe
link_to(name, '#', class: html_options[:class], data: {id: id, fields: fields})
end
end
add to your app/assets/application.js
$(document).on('click', '.custom_remove_fields', function(event) {
$(this).prev('input[type=hidden]').val('1');
$(this).closest('tr').hide();
return event.preventDefault();
});
$(document).on('click', '.custom_add_fields', function(event) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$('.contact_fields').append($(this).data('fields').replace(regexp, time));
return event.preventDefault();
});
In your template you can use the following to render a partial for the collection:
<%= link_to_add_row('contacts', contact.new, 'contact_fields', class: 'btn btn-primary') do %>
<i class="fas fa-plus"></i>
<% end %>
This is how I render the partial with the collections in my template:
<tbody class="contact_fields">
<% #contacts.each_with_index do |contact, index| %>
<%= fields_for "contacts[#{index}]", contact do |c| %>
<%= render 'contact_fields', f: c %>
<% end %>
<% end %>
</tbody>
This is what my contact_fields.html.erb partial looks like.
<tr class="nested-fields">
<td>
<%= f.text_field :fullname, class: 'form-control invoke-contacts-search contact-fullname' %>
</td>
<td>
<%= f.text_field :email, class: 'form-control invoke-contacts-search contact-email' %>
</td>
<td>
<%= f.text_field :phone, class: 'form-control contact-phone' %>
</td>
<td>
<%= f.text_field :department, class: 'form-control contact-department' %>
</td>
<td>
<%= f.text_field :manager, class: 'form-control contact-manager' %>
</td>
<td>
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
<%= link_to '#', class: 'btn btn-danger custom_remove_fields' do %>
<i class="fas fa-trash-alt"></i>
<% end %>
</td>
</tr>

Phoenix framework: Where does resource's default form #action attribute for all resources come from?

The command
mix phx.gen.html Blog Post posts title body:text
generates among other files the template form.html.eex for the add/edit posts form, which looks like this:
<%= form_for #changeset, #action, fn f -> %>
<%= if #changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
</div>
<% end %>
<div class="form-group">
<%= label f, :title, class: "control-label" %>
<%= text_input f, :title, class: "form-control" %>
<%= error_tag f, :title %>
</div>
<div class="form-group">
<%= label f, :body, class: "control-label" %>
<%= textarea f, :body, class: "form-control" %>
<%= error_tag f, :body %>
</div>
<div class="form-group">
<%= submit "Submit", class: "btn btn-primary" %>
</div>
<% end %>
The form_for function gets #action argument which is not present in the PostController, so where does it come from? I couldn't find.
In my installation I have a plug MyProject.Locale which redirects all unlocalized requests to localized ones like:
/posts --> /de/posts
And I have the :locale scope in my router
scope "/:locale", MyProject.Web, as: :locale do
pipe_through :browser
get "/", PageController, :index
resources "/posts", PostController
end
The default #action doesn't take the scope's locale chunk into account and sends the POST request to the /posts url, which is redirected by my MyProject.Locale plug to /de/posts as GET request (it uses the function Phoenix.Controller.redirect(to:...)). I want the form to send the POST request to the localized path.
So, can we override this #action argument for all resources somewhere in one place or do we have to provide it in each controller in render function call
render(conn, "new.html", changeset: changeset, action: action)
or the only option is to change the form templates for all resources?

Standard Rails form + Cocoon gem: undefined method `new_record?' for nil:NilClass error

I'm following this tutorial and the author is using Slim. Since I more familiar with standard Rails form, I try to change the slim markup to normal form like so:
new.html.erb
<%= render 'form' %>
_form.html.erb
<%= form_for(#user) do |f| %>
<%= f.text_field :name %>
<br><br>
<%= fields_for :user_photos do |photo| %>
<%= render "user_photo_fields", f: photo %>
<span class="links">
<%= link_to_add_association "add photo", f, :user_photos %>
</span>
<% end %>
<%= f.submit %>
<% end %>
_user_photo_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.file_field :photo %>
</div>
<%= link_to_remove_association "remove", f %>
</div>
And, this is my models:
class User < ActiveRecord::Base
has_many :user_photos
validates_presence_of :name
accepts_nested_attributes_for :user_photos, allow_destroy: true
end
class UserPhoto < ActiveRecord::Base
belongs_to :user
mount_uploader :photo, PhotoUploader
end
And lastly, strong params inside the users_controller.rb. I didn't touch the rest methods inside the controller because I'm using rails g scaffold user name:string generator.
def user_params
params.require(:user).permit(:name, user_photos_attributes: [:id, :photo, :_destroy])
end
I get this error:
undefined method `new_record?' for nil:NilClass
What am I missing here?
I believe it's just a simple typo - your fields_for :user_photos should be f.fields_for :user_photos (so that it's properly connected to the parent form).
please try with this.
class User < ActiveRecord::Base
has_many :user_photos
validates_presence_of :name
accepts_nested_attributes_for :user_photos, allow_destroy: true
end
can you try to fix this by removing the f
<div class="nested-fields">
<div class="field">
<%= file_field :photo %>
</div>
<%= link_to_remove_association "remove" %>
</div>

What is wrong with my coffeescript in Stripe?

I've been working on integrating Stripe into my web application, and it doesn't seem to be working. To help me along, I've been using Ryan Bates's Rails Cast on integrating Stripe. Whenever I try to run the payment form, I get an error saying that "There was a problem with my credit card". I think the problem lies in my coffeescript file, but perhaps I'm wrong. I've included the stripe user token as a part of my user model instead of placing it into its own subscription model. Here is the coffeescript code I have:
jQuery ->
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
subscription.setupForm()
user =
setupForm: ->
$('#new_user').submit ->
$('input[type=submit]').attr('disabled', true)
if $('#card_number').length
user.processCard()
false
else
true
processCard: ->
card =
number: $('#card_number').val()
cvc: $('#card_code').val()
expMonth: $('#card_month').val()
expYear: $('#card_year').val()
Stripe.createToken(card, user.handleStripeResponse)
handleStripeResponse: (status, response) ->
if status == 500
$('#user_stripe_card_token').val(response.id)
$('#new_user')[0].submit()
else
$('#stripe_error').text(response.error.message)
$('input[type=submit]').attr('disabled', false)
I'm a beginner when it comes to programming, so any help you can give me would be great.
Here's the error I get in my terminal when I try to sign up:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xas+iA+a3op7jUi57qTr7XWQSClPscA7fR19rkclkEE=", "user"=>{"stripe_card_token"=>"", "name"=>"Jack", "email"=>"email#example.com", "phone_number"=>"203-xxx-xxxx", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account"}
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('jjets718#yahoo.com') LIMIT 1
Stripe error while creating customer: Invalid token id:
My view for the signup is this:
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(#user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.hidden_field :stripe_card_token %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :phone_number, "Your cell phone number" %>
<%= f.text_field :phone_number %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Password confirmation" %>
<%= f.password_field :password_confirmation %>
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil %>
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil %>
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}%>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
My code for my controller is this for the create method:
def create
#user = User.new(params[:user])
if #user.save_with_payment
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to edit_user_path(current_user)
UserMailer.welcome_email(#user).deliver
else
render 'new'
end
end
My code for the database migration for the user token is this:
class AddStripeToUsers < ActiveRecord::Migration
def change
add_column :users, :stripe_customer_token, :string
end
end
And the code for the save_with_payment method in my model is this:
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, plan: 1, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
2 things that come to mind:
You should be doing a status check for 200, not 500
You may need to require the coffeescript file in your application.js
e.g. //= require users
I could be wrong, but at this point:
handleStripeResponse: (status, response) ->
if status == 500
$('#user_stripe_card_token').val(response.id)
In addition to changing if status == 500 to if status == 200, this line $('#user_stripe_card_token').val(response.id) may need to be $('#new_user_stripe_card_token').val(response.id). Make sure to check the input ID.

Rails 3 form_for helper not submitting action correctly

I have this form:
<% #page_title = "Delete Technician: #{#technician.name}" %>
<%= link_to("<< Back to List", {:action => 'list', :id => #technician.id}, :class => 'back-link') %>
<div class="technician delete">
<h2>Delete Technician</h2>
<%= form_for(:technician, :url => {:action => 'destroy', :id => #technician.id}) do |f| %>
<p>Are you sure you want to permanently delete this technician?</p>
<p class="reference-name"><%= #technician.name %></p>
<div class="form-buttons">
<%= submit_tag("Delete Technician") %>
</div>
<% end %>
</div>
when I click on the submit button this is the url that I get:
www.site.com/technicians/1
instead of
www.site.com/technicians/destroy/1
am I not using the form_for helper correctly or is it a configuration somewhere?
You're making this more complicated than it needs to be. There is no reason for a form when a link or a button would do. Why not just this
<p>Are you sure you want to permanently delete this technician</p>
<div> <%= link_to "Delete", technician_path(#technician), :method => :delete %> </div>
That's it.