Rails Validation Acceptance of Results in Format Error - ruby-on-rails-4

In my Author model, I'm trying to validate if the Terms are accepted.
In schema, I have the field tos as a Boolean.
In the model, I have this for validation:
validates_acceptance_of :tos, :accept => true
In my form:
<%= content_for(:the_links) do %>
I agree to the <%= link_to "Terms of Service", tos_path,:remote => true %>
and <%=link_to "Privacy Policy", "#", :remote => true%>
<% end %>
<%= simple_form_for(#author) do |f| %>
<%= f.input :tos, :as => :boolean, label: false, boolean_style: :inline, :hint => content_for(:the_links)%>
<%= f.button :submit %>
<% end %>
The error I receive:
ActionController::UnknownFormat in AuthorsController#create
ActionController::UnknownFormat
The parameters look this this:
{"utf8"=>"✓",
"author"=>{
"tos"=>"0"},
"commit"=>"Create Author"}
My problem seems slightly different than this issue:
Validates acceptance always failing
but I have also tried:
deleting the attribute from the database
changing the validation to: validates :terms, :acceptance => {:accept => true}
Yet, I still get the format error.
Adding create action
def create
#author = Author.new(author_params)
#author.user_id = current_user.id
respond_to do |format|
if #author.save
merchant_account_params = {
:individual => {
:first_name => #author.first_name,
:last_name => #author.last_name,
:email => current_user.email,
:date_of_birth => #author.dob,
:ssn => #author.ssn,
:address => {
:street_address => #author.indiv_street,
:locality => #author.indiv_city,
:region => #author.indiv_state,
:postal_code => #author.indiv_postal_code
}
},
:business => {
:legal_name => #author.legal_name,
:dba_name => #author.dba,
:tax_id => #author.ein,
:address => {
:street_address => #author.bus_street,
:locality => #author.bus_city,
:region => #author.bus_state,
:postal_code => #author.bus_postal_code
}
},
:funding => {
:destination => "email",
:email => #author.venmo_email,
},
:tos_accepted => #author.tos,
:master_merchant_account_id => BT_SANDBOX_MASTER_MERCHANT,
:id => #author.id
}
result = Braintree::MerchantAccount.create(merchant_account_params)
if result.success?
#author.update(:status=>result.merchant_account.status)
format.html { redirect_to #author, notice: 'Author was successfully created.' }
format.json { render :show, status: :created, location: #author }
else
format.html { render :new }
format.json { render json: #author.errors, status: :unprocessable_entity }
end
end
end
end

Related

"data has contents that are not what they are reported to be" paperclip with ckeditor

I am using paperclip with ckeditor and I get this error when i click on "send it to the server" : "data has contents that are not what they are reported to be".
That's what "attachment_file.rb" and "picture.rb" look like:
class Ckeditor::AttachmentFile < Ckeditor::Asset
has_attached_file :data, :styles => { :content => '575>', :thumb => '80x80#' },
:storage => :s3, :s3_credentials => "/config/s3.yml", :path => ":attachment/:id/:style.:extension",
:url => ":s3_domain_url"
validates_attachment_presence :data
validates_attachment_size :data, less_than: 100.megabytes
do_not_validate_attachment_file_type :data
def url_thumb
#url_thumb ||= Ckeditor::Utils.filethumb(filename)
end
end
you should remove the do_not_validate_attachment_file_type :data line from your code, or just change the editor .

Strong parameters with Rails 4.0 and Devise

I am using Rails 4.2 and devise.Request type will always be JSON.My registrations controller looks like this
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_sign_up_params, only: [:create]
def create
if request.format(request) == "application/json"
build_resource(sign_up_params)
if resource.save
render :json => {:success => "true", :message => "Thank You For Registering."}
else
render :json => {:success => "false", :message => resource.errors.full_messages}
end
else
super
end
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
end
The parameters that show-up in the console is like :
Parameters: {"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration"=>{"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
The error it produces is that the controller doesn't recognize the email and password fields and always returns error like :
["Email can't be blank","Password can't be blank"]
Does this happen because of any foolishness that I have written in the code?Please help
Your configure_sign_up_params method has to be something like this to work.
def configure_sign_up_params
devise_parameter_sanitizer.for(:registration) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
If you can see the console content what you have posted, it contains a hash with registration as a key:
"registration"=>{"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}

rails 4.1 Activeadmin with paperclip, add image button pressed no response

I want to upload images to a place in active admin dashboard by paperclip, but When i pressed "add new place picture", nothing happened. Image as below:
model/place.rb
class Place < ActiveRecord::Base
has_many :place_pictures, :dependent => :destroy,
:autosave => true
accepts_nested_attributes_for :place_pictures,
:allow_destroy => true
end
model/place_picture.rb
class PlacePicture < ActiveRecord::Base
belongs_to :place
attr_accessible :picture, :logo
has_attached_file :picture, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :picture, :content_type => /\Aimage\/.*\Z/
end
admin/place.rb
ActiveAdmin.register Place do
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs "Place details" do
f.input :name
f.input :about
f.has_many :place_pictures do |ff|
ff.input :picture, :as => :file, :hint => ff.template.image_tag(ff.object.picture.url(:thumb))
ff.input :logo, as: :boolean, :label => "isLogo"
end
end
f.actions
end
index do
column :id
column :name
column :city
column :about
column "Images" do |place|
if !(place.place_pictures.empty?)
ul do
place.place_pictures.each do |img|
li do
image_tag(img.picture.url(:thumb))
end
end
end
end
end
actions
end
show do |ad|
attributes_table do
row :name
row :city
row :about
row :image do
if !(place.place_pictures.empty?)
ul do
place.place_pictures.each do |img|
li do
image_tag(img.picture.url(:thumb))
end
end
end
end
end
end
#active_admin_comments
end
end
Gemfile:
gem 'rails'#version 4.1.8
gem 'activeadmin', github: 'activeadmin'
gem "paperclip", "~> 4.2"
It worked well before on rails 3.x and active_admin 0.6.x. Any help? thanks!
UPDATE:
Finally change active_admin.js to below, it works! don't know why! hope help anyone if has this situation.
// = require jquery
// = require jquery_ujs
// = require active_admin/base
It seems the javascript that appends the fields (has_many), doesn't work. Do you have any JavaScript runtime on your system? Node.js for example.
https://github.com/sstephenson/execjs

appending parameters to request in an api controller spec

I am sending requests to my API in the following format
http://server/url?v=HEAD&access_token=TOKEN
My question is how do I append the v parameter and access_token parameter in my requests within the controller specs?
Below is a sample of what I have so far. None of it works:
describe Api::ShopsController do
let(:application) { Doorkeeper::Application.create(:name => "MyApp", :redirect_uri => "http://app.com") }
let(:user) { FactoryGirl.create(:user) }
let(:token) { Doorkeeper::AccessToken.create! :application_id => application.id, :resource_owner_id => user.id }
describe "GET #index" do
it "should respond with 200" do
get :index, :format => :json, :access_token => token.token
response.status.should eq(200)
end
it "should list all shops" do
Shop.should_receive(:all) { [] }
get :index, :format => :json, :access_token => token.token
response.body.should == [].to_json
end
end
# Example url: localhost:3000/shops/1?v=HEAD&access_token=TOKEN
describe "GET show" do
it 'responds with 200' do
shop = Shop.create! FactoryGirl.attributes_for :shop
get :show, {id: shop.id, :access_token => access_token.token, v: "HEAD"}, :format => :json
response.status.should eq(200)
end
it "returns the requested shop" do
shop = Shop.create! FactoryGirl.attributes_for :shop
get :show, {:id => user.to_param}, :format => :json, :access_token => token.token
assigns(:user).should eq(user)
end
end
did you try this?
get shop_path(id: shop.id, v: 'HEAD', access_token: token.token, format: :json)

Mongoid Model won't persist has_one via embeds_one relation

I'm having trouble with embeds in a mongoid4-based rails 4 app. I've been looking for an answer everywhere for the past 2 days. So here is the code.
This is a church management app, with a Service model, embedding a team and a band. Each team/band has several roles such as "presidence", "communion" that refer to a user.
My models :
class Service
include Mongoid::Document
...
embeds_one :team, autobuild: true
embeds_one :band, autobuild: true
...
accepts_nested_attributes_for :team, :band
end
class Team
include Mongoid::Document
embedded_in :service
has_one :presidence, :class_name => 'User', autosave: true
has_one :message, :class_name => 'User', autosave: true
...
end
class Band
include Mongoid::Document
has_one :lead, :class_name => 'User', autosave: true
has_one :guitar, :class_name => 'User', autosave: true
...
embedded_in :service
end
class User
include Mongoid::Document
embeds_one :profile
belongs_to :team, :inverse_of => :presidence
belongs_to :team, :inverse_of => :message
belongs_to :band, :inverse_of => :lead
belongs_to :band, :inverse_of => :guitar
def fullname
"#{profile.firstname} #{profile.lastname}"
end
def self.find_by_talent(talent)
self.where("profile.talents.name" => talent)
end
end
The services controller :
# POST /services
# POST /services.json
def create
#service = Service.new(service_params)
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render action: 'show', status: :created, location: #service }
else
format.html { render action: 'new' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
...
def service_params
params.require(:service).permit(:date, :time, :place, :name, :theme, :team => [:id, :precedence, :message ], :band => [:id, :lead, :guitar ])
end
And the form in _form.html.erb :
<%= form_for(#service) do |f| %>
...
<%= f.fields_for #service.team do |tf| %>
<%= tf.collection_select :presidence, User.find_by_talent(:presidence), :_id, :fullname, {:include_blank => "select a person"} %>
<%= tf.collection_select :message, User.find_by_talent(:message), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
<%= f.fields_for #service.band do |bf| %>
<%= bf.collection_select :lead, User.find_by_talent(:lead), :id, :fullname, {:include_blank => "select a person"} %>
<%= bf.collection_select :guitar, User.find_by_talent(:guitar), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
...
<% end %>
When creating a service, everything seems to run fine, but this is what I get in the console :
2.0.0-p195 :001 > s = Service.last
=> #<Service _id: 52ea18834d61631e7e020000, date: "2014-02-02", time: "10:00", place: "Where it's at", name: "My great name", theme: "The service's theme">
2.0.0-p195 :002 > s.team
=> #<Team _id: 52ea18834d61631e7e030000, >
2.0.0-p195 :003 > s.team.presidence
=> nil
Why is s.team.presidence not created ? s.team looks weird, too, with an ending comma...
Here is the content of my rails log :
Started POST "/services" for 127.0.0.1 at 2014-01-30 10:16:51 +0100
Processing by ServicesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ph6lbdHC2FbiANn/fGSzHWprenj3fWKXM40Hrsc5+AM=", "service"=>{"date"=>"2014-02-02", "name"=>"My great name", "theme"=>"The service's theme", "time"=>"10:00", "place"=>"Where it's at", "team"=>{"presidence"=>"52ea18324d61631e81010000", "message"=>"52ea18324d61631e81010000"}, "band"=>{"lead"=>"52ea18324d61631e81010000", "guitar"=>"52ea18324d61631e81010000"}}, "commit"=>"Create Service"}
MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} runtime: 0.6610ms
MOPED: 127.0.0.1:27017 UPDATE database=service_boot_camp_development collection=users selector={"band_id"=>BSON::ObjectId('52ea18834d61631e7e010000'), "_id"=>{"$nin"=>[]}} update={"$set"=>{"band_id"=>nil}} flags=[:multi]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 0.5800ms
MOPED: 127.0.0.1:27017 INSERT database=service_boot_camp_development collection=services documents=[{"_id"=>BSON::ObjectId('52ea18834d61631e7e020000'), "date"=>"2014-02-02", "time"=>"10:00", "place"=>"Where it's at", "name"=>"My great name", "theme"=>"The service's theme", "team"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e030000')}, "band"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e010000')}}] flags=[]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 2.7460ms
I guess I'm doing something wrong, but I have no clue if it is in the database model or in the form... or anything else...
You will not be able to do it this way. When you create an embedded document, its _id and all of its data are embedded directly within the parent document. This is in contrast to an association, where the document with the belongs_to gets a foreign key which points to its associated parent document. So here, your User documents each have a team_id and band_id, but when the database tries to get the documents, it can't find them, since you can't query directly for embedded documents; you need the parent document first. For more, see the Mongoid documentation.
Another potential issue is that you have multiple belongs_to definitions in the User models. This will also cause an issue, because for each one of those, Mongoid will attempt to create a team_id and band_id. You should name them separately and specify a class name; perhaps names like :presiding_team and :message_team, :lead_band and :guitar_band, etc. This answer should show you what that would look like.
I would recommend making the Team and Band separate referenced documents instead of embedded documents, since you won't be able to reference users effectively while they're embedded.
Hope this helps.