795: unexpected token at in POST + Ruby on Rails - ruby-on-rails

I'm trying to put together the postman a POST call to yell my class these are my model and controller
#yell.rb
class Yell < ActiveRecord::Base
include ActionView::Helpers::DateHelper
belongs_to :user, inverse_of: :yells
has_many :negotiations, inverse_of: :yell, :dependent => :delete_all
has_one :trade_offer, inverse_of: :yell, :dependent => :destroy
has_and_belongs_to_many :categories, inverse_of: :yell, :dependent => :delete_all
def as_json(options={})
super(:only => [:id, :yell_type, :status, :payment_type],
:include => {
:trade_offer => {:only => [:id, :title, :description, :price],
:include => [:photos => {:only => [:id],
:methods => :url}]
},
:categories => {:only => [:id, :name]},
:user => {:only => [:id, :name, :avatar]}
},
:methods => [ :times_ago]
)
end
def times_ago
time_ago_in_words(self.created_at)
end
def url
self.trade_offer.photos.url.url
end
end
#yells_controller.rb
# POST /yells.json
def create
if (YELLTYPES[0][YELLTYPE_OFFER].include? params[:yell_type]) || (params[:yell_type].equal? YELLTYPE_REQUEST_BUY)
#yell = Yell.new(yell_params)
#user = User.find_by_id(params[:user_id]) #just have it because it has not current_user
#yell.user = #user
if #yell.save
#creating an offer on a yell
#trade_offer = TradeOffer.new(trade_offer_params)
#trade_offer.yell = #yell
if #trade_offer.save
#yell.trade_offer = #trade_offer
else
#yell.destroy
render json: {status: 3, message:"offer not create", data: nil}, status: :unprocessable_entity
return
end
#categories relating to yell if the category does not exist it will be created
Array(params[:yell][:categories]).each do |rel|
#category = Category.find_by_name(rel[:name])
if #category
#categories_yells = CategoriesYell.new(category_id: #category.id, yell_id: #yell.id)
if #categories_yells.save
#yell.categories.build(id: #category.id, name: rel[:name])#only creates the relationship
else
#yell.destroy
render json: {status: 4, message:"relationship category not create", data: nil}, status: :unprocessable_entity
end
else
#yell.categories.create(name: rel[:name]) #creates the relationship and category
end
end
#creating photos related to an offer
Array(params[:yell][:trade_offer][:photos]).each do |rel|
#photo = Photo.new(url: rel, trade_offer_id: #trade_offer.id)
if !#photo.save
#yell.destroy
render json: {status: 5, message:"photo not upload", data: nil}, status: :unprocessable_entity
return
end
end
render json: {status: 0, message:"succes", data: #yell}, status: :created
else
render json: {status: 6, message:"yell not create", data: nil}, status: :unprocessable_entity
end
else
render json: {status: 7, message:"type not permitted", data: {types_permitted: YELLTYPES}}, status: :unprocessable_entity
end
end
the idea is to go to a scream a category of series and a series of images. This call worked perfectly when the body one step aplication / json, but with this I can not upload images.

I was going to call the header content-type = aplication/json, just had to take it, and added to my route defaults: {format: 'json'}

Related

Include "distance_of_time_in_words" value in JSON output

I have an index action in my controller that I use to render all posts as JSON:
def index
#user = current_user
#posts = Post.all
end
respond_to do |format|
format.html
format.json {
render json: #posts.to_json(:include => {
:user => { :only => [:first_name, :last_name]},
:category => { :only => [:name, :id]}
}),
:callback => params[:callback]
}
end
end
What I'd like to do, is add an additional attribute to each post's JSON output called posted_on, that has a value of: distance_of_time_in_words(post.created_at, Time.now)}
I can't seem to be able to figure out how to approach this. Any help would be appreciated!
Add the method posted_on to Post model
class Post < ActiveRecord::Base
include ActionView::Helpers::DateHelper
def posted_on
distance_of_time_in_words(created_at, Time.now)
end
end
In your controller, pass the methods option to to_json
def index
#user = current_user
#posts = Post.all
end
respond_to do |format|
format.html
format.json {
render json: #posts.to_json(:include => {
:user => { :only => [:first_name, :last_name]},
:category => { :only => [:name, :id]}
}, :methods => :posted_on),
:callback => params[:callback]
}
end
end

How to modify a json response to include own keys instead it being created by itself in rails?

I have two models category and sub_category
class Category < ActiveRecord::Base
has_many :sub_categories
and
class SubCategory < ActiveRecord::Base
belongs_to :category
now in my sub_category controller i have
#sub_category = SubCategory.paginate(:page => params[:page], :per_page => params[:per_page]).all(:order => 'id ASC')
respond_to do |format|
format.json { render json: {:sub_category => #sub_category.as_json(:only => [:id, :name, :category_id, :created_at, :updated_at])} }
end
but i want the category object to which the subcategory belongs_to within this as shown below
[
{
"sub_category":
[{
"created_at":"2013-09-25T07:16:53Z",
"id":2,
"name":"mobile",
"updated_at":"2013-09-25T07:19:39Z"
"category":{"id":1, "name":"gadgets"}
}]
}
]
How can i do it? Please help me.
This should work:
#sub_category = Subcategory.paginate(:page => params[:page], :per_page => params[:per_page]).order('id ASC').includes(:category)
respond_to do |format|
format.json { render json: {:sub_category => #sub_category.as_json(
:only => [:id, :name, :category_id, :created_at, :updated_at],
:include => {:category => {:only => [:id, :name])} }
end

Cannot favorite users using polymorphic association

Using the system below users are able to favorite styles in the format of:
=> #<Favorite id: 59, user_id: 2, favoritable_id: 15, favoritable_type: "Style", created_at: "2013-04-06 08:47:08", updated_at: "2013-04-06 08:47:08">
I have built the system to enable users to favorite users as well, but for some reason the line Favorite.create!(:user => user) is not creating the expected favorite model object when called on User, as above when called on Style. Instead I am getting nils as below:
=> #<Favorite id: 65, user_id: 2, favoritable_id: nil, favoritable_type: nil, created_at: "2013-04-06 09:35:07", updated_at: "2013-04-06 09:35:07">
Problem is above. Details are below
Favorite Class:
class Favorite < ActiveRecord::Base
belongs_to :favoritable, :polymorphic => true
belongs_to :user
attr_accessible :user
validates_presence_of :user
validates_uniqueness_of :user_id, :scope => [:favoritable_type, :favoritable_id]
end
Model definitions including favoritable module (see below):
class User < ActiveRecord::Base
include Favoritable
class Style < ActiveRecord::Base
include Favoritable
Favoritable Module:
module Favoritable
extend ActiveSupport::Concern
included do
attr_accessible :favorites
has_many :favorites, :as => :favoritable, :autosave => true
accepts_nested_attributes_for :favorites
def add_favorite(user)
self.favorites << Favorite.create!(:user => user)
save
end
def delete_favorite(user)
self.favorites.where(:user_id => user.id).each do |favorite|
favorite.destroy
end
end
end
end
Favorites Controller:
class FavoritesController < ApplicationController
def fav_user
#user = User.find(params[:id])
#user.add_favorite(current_user)
respond_to do |format|
format.js { render :action => "update_favorite_disp", :layout => false }
end
end
def delete_fav_user
#user = User.find(params[:id])
respond_to do |format|
if #user.delete_favorite(current_user)
format.js { render :action => "update_favorite_disp", :layout => false }
end
end
end
def fav_style
#style = Style.find(params[:id])
#style.add_favorite(current_user)
respond_to do |format|
format.js { render :action => "update_favorite", :layout => false }
end
end
def delete_fav_style
#style = Style.find(params[:id])
respond_to do |format|
if #style.delete_favorite(current_user)
format.js { render :action => "update_favorite", :layout => false }
end
end
end
end
You need to pass in the :favoritable model in add_favorite:
def add_favorite(user)
Favorite.create!(:user =>user, :favoritable => self)
save
delete_favorite also needs to delete based on the :favoritable_id, instead of :user_id:
def delete_favorite(user)
user.favorites.where(:favoritable_id => self.id).each do |favorite|
favorite.destroy
end
end

ActiveRecord::AssociationTypeMismatch on many to many relaitonship

Hello I am trying to build a multi select to populate a many-to-many join table. I am able to crate the new newform but am getting "AssociationTypeMismatch" when I try to save my record.
The solutions that I am finding on the web are not solving my problem.
Hoping someone can resolve what I should be doing to get rid of "AssociationTypeMismatch"
class Presenter < ActiveRecord::Base
belongs_to :seminar
belongs_to :person
end
class Seminar < ActiveRecord::Base
attr_accessible :description, :title,
has_many :presenters, :foreign_key => "person_id"
has_many :lecturer, :through => :presenters, :source => :person
accepts_nested_attributes_for :lecturer, :presenters
end
class Person < ActiveRecord::Base
attr_accessible :first_name, :last_name
has_many :presentors
has_many :lecturingAt, :through => :presentors
def fullName
first_name + " " + last_name
end
end
seminars_controller.rb
def new
#seminar = Seminar.new
#current_presenters = Person.find(:all)
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #seminar }
end
end
....
def create
#seminar = Seminar.new(params[:seminar])
respond_to do |format|
if #seminar.save
format.html { redirect_to(#seminar, :notice => 'Seminar was successfully created.') }
format.xml { render :xml => #seminar, :status => :created, :location => #seminar }
else
format.html { render :action => "new" }
format.xml { render :xml => #seminar.errors, :status => :unprocessable_entity }
end
end
end
Seminars/_form.html.erb. has which populates my collection select with the names and persion ids of
possible lecurers.
....
<div class="field">
<%= f.label :presenter_id %><br />
<%= collection_select(:seminar,:lecturer,#current_presenters, :id, :fullName,{}, {:multiple=>true} ) %>
....
On submitting the params passed into my controller
Parameters: {...., "seminar"=>{ "lecturer"=>["1", "2"], "title"=>"1234567890", "description"=>"ASDFGHJKL:"}, "commit"=>"Create Seminar"}
Getting error:
ActiveRecord::AssociationTypeMismatch (Instructor(#86075540) expected, got String(#73495120)):.
#seminar = Seminar.new
Try this
#seminar.lecturer_ids = params[:seminar].delete(:lecturer)
#seminar.update_attributes(params[:seminar])

Polymorphic nested form results in AssociationTypeMismatch

Models:
class User < ActiveRecord::Base
belongs_to :role, :polymorphic => true
class Admin < ActiveRecord::Base
has_one :user, :as => :role
class Dealer < ActiveRecord::Base
has_one :user, :as => :role
class Buyer < ActiveRecord::Base
has_one :user, :as => :role
Dealer controller:
def new
#dealer = Dealer.new
respond_to do |format|
format.html
format.xml { render :xml => #dealer }
end
end
def create
#dealer = Dealer.new(params[:dealer])
respond_to do |format|
if #dealer.save
flash[:notice] = 'Dealer was successfully created.'
format.html { redirect_to [:admin, #dealer] }
format.xml { render :xml => #dealer, :status => :created, :location => #dealer }
else
format.html { render :action => "new" }
format.xml { render :xml => #dealer.errors, :status => :unprocessable_entity }
end
end
end
Error message:
ActiveRecord::AssociationTypeMismatch in Admin/dealersController#create
User(#41048900) expected, got HashWithIndifferentAccess(#23699520)
Request Parameters:
{"authenticity_token"=>"+GkeOOxVi1Fxl7ccbV0Ctt5R6shyMlF+3UWgRow2RdI=",
"dealer"=>{"gender"=>"m",
"forename"=>"",
"surname"=>"",
"company"=>"",
"address1"=>"",
"address2"=>"",
"zipcode"=>"",
"city"=>"",
"country"=>"1",
"user"=>{"email"=>"",
"password"=>""},
"phone"=>"",
"mobile"=>"",
"fax"=>""},
"commit"=>"Submit"}
I guess my problem is that Rails doesn't convert the "user" hash inside the request hash into a User object — but why and how can I make Rails to do that?
Just spent several hours on this including bumping into this thread. Finally found on another forum:
the attribute setter expects to get your params in this form
{ ...,
"user_attributes" => {"email" => "", "password" => ""},
... }
NOT
{ ...,
"user" => {"email" => "", "password" => ""},
... }
In order to get this, your view should look something like this:
form_for #dealer do |f|
...
f.fields_for :user, #dealer.user do |u|
...
end
...
end
This works for me on Rails 3.0.3

Resources