Radio button not working in rails form - ruby-on-rails-4

I want to create a form where i will be having 2 radio buttons. one for 'public' and onother for 'private'.
I have a User model in my project and i have privacy field in it which is boolean and its default value is true(that is 'public' in my case).
I have update button in my form. I want to submit the form and accordingly want to update the value in User model. and then if whenever i visit edit page the corresponding radio button should be selected.
This is my form
= form_tag "/users/abc" do
%p.heading We Respect Your Privacy
.privacy
%input#r1{:name => "privacy", :type => "radio", :value => 0}
%label.privacyLabel{:for => "r1"}
%span>
Friends Only
%p
TraveLibro enables you to save your travel memories and share them with your friends. While other TraveLibro users
can see your itineraries, only your friends on TraveLibro can view your personal pictures.
%br
%p Now you can upload all your captured memories without ever having to be concerned about your privacy.
.privacy
%input#r2{:name => "privacy", :type => "radio", :value => 1}
%label.privacyLabel{:for => "r2"}
%span>
Everyone
%p
Want to share your travel tales with the world. With an open profile TraveLibro users can view the itineraries
you have created and the pictures that complete those memories.
.privacyUpdate
%a{:href => "javascript:void(0);"}
%input.privacyUpdateBtn{:type => "submit", :value => "update"}/
and this is my controller action
def abc
current_user.update_column('privacy', params[:privacy] == 0 ? 0 : 1)
redirect_to :back
end
But its not working

Try this:
def abc
current_user.update_column('privacy', params[:privacy].to_i == 0 ? 0 : 1)
redirect_to :back
end

Related

call object in another controller before save rails 4

I have an object called reportapproval. I start the object in a form and before it is saved I want it to go thru a charge controller. If the charge does not go thru then it wont save the object but if it does then it will save.
I am trying to pass the unsaved object to the charge controller. How can I do this. Here are the 2 actions in their respective controller.
reportapproval_controller.rb
def create
#reportapproval = current_manager.reportapprovals.new(authorization_params)
if #reportapproval.valid?
if #reportapproval.manager_paying_report == true
flash[:notice] = "Please make payment before proceeding"
redirect_to new_managers_charge_path(id: #reportapproval_id)
charge_error = nil
end
end
end
charge_controller.rb
def create
# Amount in cents
#reportapproval = Reportapproval.new(session[:reportapproval_id])
#manager = current_manager
#amount = #reportapproval.manager_request_report_type
customer = Stripe::Customer.create(
:email => #manager.email,
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
...
)
#reportapproval.report_paid = true
#reportapproval.save!
redirect_to managers_dashboard_path, :notice => "You have successfully ..."
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to managers_charges_path
end
end
How can I pass this object to the charge and then back to the reportapproval before saving to the DB. I am using mongoid btw.
Thanks in advance.
You can but you shouldn't do that. Save the Reportapproval with a flag to indicate that it hasn't been paid for yet. After the Stripe procedure went through remove the flag to allow the user full access.
Btw, this will also help you find out wether and how many user do stop during the Stripe procedure and not come back again.

Rolify and Rails 4 role management

I am trying to implement a role based access system in my rails 4 app, and I want the end user (super_admin) to have the ability to edit role assignments via the UI.
I have achieved some success but can't help feeling that there has to be a better way (Since I'm new to rails). Here is my code:
users_roles_controller.rb
# GET /user_roles/new/:id
def new
#roles = Role.all
end
# POST /user_roles/new/:id
def create
populated = params[:roles][:name].reject(&:empty?)
populated.each do |key|
#user.add_role Role.find(key).name
end
redirect_to users_path
end
And in my Form (HAML and simple_form):
= simple_form_for :roles, :url => create_user_roles_path(#user.id), :method => "post" do |f|
= f.input :name, :collection => #roles, as: :check_boxes
= f.button :submit
I'm struggling with the following:
How do I validate form entries, since there is no model?
Should I be using strong parameters and if so how do I implement on a form without a model
How do I create something similar, but with Current roles already checked? (True role management)
UPDATE
I have looked at using the reform Gem as suggested by the comments. This seems like a great solution. I am however having issues with the implementation on this case.
Let me map it out:
I have 3 tables in the database:
users
users_roles (Mapping Table with 2 Attributes : user_id & role_id {Join Table -> HABTM})
roles
I want to construct a form with all the values in the Roles model as checkboxes.The checkboxes should dictate what values are fed into the users_roles table (With relation to a specific user). What I want reform to do is validate the input of this form. This form will always display all of the values in Roles, but some/all of the boxes might be unchecked.
I have created a form folder in my app and started with the following code:
class UserRoleForm < Reform::Form
property :user__id, on: :user
property :role_id, on: :role
validates :user__id, presence: true
validates :role__id, presence: true
end
Am I going in the right direction?
Thanks for the help.
You need two things to build your form: a user's roles and the possible roles.
If I recall correctly, rolify gives your model associations ad should just let you do something like some_user.roles to return all the roles applied to some_user.
To get possible roles, try Role.all.
To combine both, try
user_roles = some_user.roles.pluck(:name) # suppose this returns ["admin"]
Role.pluck(:name).map { |r| [r, user_roles.include?(r)] }
You now have an array like this that you can use to build your form checkboxes with an each loop.
[["customer", false], ["admin", true], ["editor", false]]
Define your reform object's sync or save method to handle what to do with the submitted input, however you are handling it. You can (SHOULD) make a custom validation to verify if the submitted roles are valid roles.

Rspec/Capybara not displaying expected results for cache_counter

The problem is the results printed to the screen by capybara/rspec are different to the values in the database.
Background
- I have a many-to-many relationship between promo and products.
- Promo has a products_counter column to keep track of the number of products related to a promo. This is handled with counter_cache on the association.
- This functionality is working. I have tested it through the front end - basic crud functionality - and all the data is correct on the front end.
Something is happening and I can't figure it out. My spec fails because the page does not have the value '1' on it which is the product count. The page instead has 2 for the product count on the page.
I thought that this issue could be a point in the right direction, but I had no luck with that and there isn't much else on google.
See spec below.
require 'rails_helper'
include Warden::Test::Helpers
Warden.test_mode!
feature 'Promo index page' do
scenario 'displays a list of promos' do
admin = create(:user, :admin)
p1 = create(:promo)
p1.products << create(:product)
login_as(admin)
visit promos_path
puts p1.products.count # => 1 in console
puts p1.products_count # => 1 in console
# save_and_open_page => this gives me a view into the page
# on the browser - lets me see that product count is printing
# to the screen as 2
expect(page).to have_text p.code
expect(page).to have_text p.name
expect(page).to have_text p.products.count # => fails because page displays 2 instead of 1
end
end
I have included the view for those that want to see how it's being rendered.
header.full-width-row
.columns.large-12
= link_to 'New Promo', new_promo_path, class: 'right button tiny radius'
section.full-width-row
.columns.large-12
table.full-width
thead
tr
td = "Code"
td = "Name"
td = "Product Count"
tbody
- #promos.each do |p|
tr
td.filter-on = p.code
td.filter-on = link_to p.name, promo_path(p)
td = p.products_count
Any help appreciated.

Rails 4 and Active Admin: ActiveModel::ForbiddenAttributesError

The full error is the following:
ActiveModel::ForbiddenAttributesError in Admin::ProductsController#create
My product model only has a name and price. Why is commit a parameter? When I click the 'Create Product' button within the admin dashboard, this is the params output:
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"6/pCeklsaik4sYF5h8+WRPddkH7wJn9ZJHd6YLaaNuc=",
"product"=>{"name"=>"Black Shirt Male",
"price"=>"25"},
"commit"=>"Create Product"}
From what I've gathered reading other Stack Overflow posts, you need to use strong parameters in Rails 4 instead of attr_accessible, which was done for me when I scaffolded the product model. In my create action in the Products controller, I have:
#product = Product.new(product_params)
And product_params is defined as:
def product_params
params.require(:product).permit(:name, :price)
end
I didn't do anything fancy when I created the model, and in my Gemfile I'm using the following as the documentation suggested for Rails 4:
gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'
Why am I getting this error when I create a new product via the Active Admin dashboard? Any input on the matter is appreciated.
Alright figured it out. I'm not sure if this is the 'correct' way but the products are being created.
in app/admin/product.rb I did:
permit_params :list, :of, :attributes, :on, :model, :name, :price
where
permit_params :list, :of, :attributes, :on, :model
was initially commented out. So I just added :name and :price
Question already answered, but I'm adding this as a helpful resource to supplement this answer:
https://github.com/activeadmin/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters

View overriding using Deface

I am trying to insert a text on show page of Spree's product page.
My app/overrides/show_new.html.erb as follows:
Deface::Override.new(:virtual_path => "spree/products/show",
:insert_after => "[data-hook='product_show']",
:text => "<p>This is overriding......</p>",
:name => "show_new",
:disabled => false)
But, the view is not overridden. Am I missing something?
You must restart your app for the overrides to register first.
Otherwise, this seems correct (assuming your code is in app/overrides/something.rb)
Watch out if you are not on latest version, some views HTML are broken and it breaks deface.
https://github.com/spree/spree/issues/1056 (I ran into this issue last week)