My goal is an output like this (for each attachment):
url:
"/uploads/attachment/picture/15/5ee306c9-e263-466b-b56d-1c7c9d2ae17b.jpg"
What I have at the moment:
attachments_controller.rb
class AttachmentsController < ApplicationController
before_action :logged_in_user
def index
#attachments = current_user.attachments.all
respond_to do |format|
format.json do
render :json => #attachments.each{ |o| o.picture.url }
end
end
end
...
Try
respond_to do |format|
format.json do
render :json => #attachments.map { |o| { url: o.picture.url } }
end
end
Related
I'm using Rails 4.0.2 with paperclip for image upload in my project. Also I need to send a full image path of paperclip. So I can do it with add new field and set image path manually in my show controller method for particular record.
show
def show
respond_to do |format|
format.html
format.json { :json => JSON::parse(#demo.to_json.merge("new_field" => #demo.image_url.url).to_json}
end
end
When I view Json for any of my record, this is will showing good.
{
id: "1",
name: "demo",
new_field: "/demo/1/original/file.jpg"
}
In same scenario, I need to get the full image path of paperclip image for all records when I am requesting to index method on controller
index
def index
#demos = Demo.all
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
I tried some of codes, but I don't know how exactly to write
def index
#demos = Demo.all
#demos.each do |demo|
new_field = {"new_field" => #demo.image_url.url}
# After I stucked with logic, how to uppend with 'demo'.
end
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
How do I iterate my individual Demo model and How to merge full image path into each record.
I found the solution for my question,
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
new_field = {"new_field" => #demo.new_field.url}
demo = JSON::parse(demo.to_json).merge(new_field)
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
I suggest you to use two approaches, 1)use active model serializer to expose json response. 2) use jbuilder library to expose custom fields. Still you need help please let me know.
Try this:-
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
demo["new_field"] = #demo.image_url.url
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
maybe you can try:
def index
#demos = Demo.all
#demos.map do |demo|
new_field = {"new_field" => #demo.image_url.url}
demo.attributes.merge(new_field)
end
respond_to do |format|
format.html
format.json { :json => #demos}
end
end
attributes method returns a hash of all the object attributes, just need merge new key-value into the returned hash.
Another way of doing it is in your controller where you are rendering the json
render json: #merchants,
include: {
offers: {
except: [:created_at, :updated_at],
include: {
categories: {
except: [:created_at, :updated_at]
}
}
},
location: {
methods: :country_name,
except: [:created_at, :updated_at]
}
},
except: [:created_at, :updated_at]
Note the methods: :country_name, there you can render methods from your model as json attributes. and through include: ... you can eager load and render related models.
I'm following the tutorial here: https://egghead.io/lessons/angularjs-rails-todo-api-part-1 but I end up getting that error when I hit this on my localhost: /api/v1/todos
routes.rb:
namespace :api, defaults: {format: :json} do
namespace :v1 do
resources :todos
end
end
controllers/api/v1/todos_controller.rb
module Api
module V1
class TodosController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json
def index
respond_with(Todo.all.order("completed ASC").order("id DESC"))
end
def show
#todo = Todo.find(params[:id])
respond_with(#todo)
end
def create
#todo = Todo.new(todo_params)
if #todo.save respond_to do |format|
format.json { render :json => #todo }
end
end
def update
#todo = Todo.find(params[:id])
if #todo.update(todo_params)
respond_to do |format|
format.json { render :json => #todo }
end
end
end
def destroy
respond_with Todo.destroy(params[:id])
end
private
def todo_params
params.require(:todo).permit(:title, :completed)
end
end
end
end
for some reason there was an end missing. I can't figure out where it's connected to, but throwing an end at the end of the file fixed this error.
change
def create
#todo = Todo.new(todo_params)
if #todo.save respond_to do |format|
format.json { render :json => #todo }
end
end
to
def create
#todo = Todo.new(todo_params)
if #todo.save
respond_to do |format|
format.json { render :json => #todo }
end
end
end
I want to override Kaminari's pagination when rendering JSON, or tell it to return all with pagination.
In App1, I am using ActiveResource to access App2's Group model:
class Group < ActiveResource::Base
self.site = "http://www.app2.com:3000"
end
Here's App2's Group model:
class Group < ActiveRecord::Base
default_scope order('name asc')
paginates_per 10
This is my controller. The Group.search stuff is ransack:
class GroupsController < ApplicationController
# GET /groups
# GET /groups.json
def index
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #groups }
end
end
I've added eleven groups to App2. In the console of App1 I get:
[45] pry(main)> Group.all.count
=> 10
What is the best way to do this without changing the HTML pagination rendering?
You can prepare all the common logic you need but only apply pagination for the HTML format:
def index
#search = Group.search(params[:q])
#groups = #search.result
respond_to do |format|
format.html { #groups = #groups.page(params[:page]) }
format.json { render :json => #groups }
end
end
You can run different code in different formats:
def index
respond_to do |format|
format.html {
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
} # index.html.erb
format.json {
render json: Group.all
}
end
end
I have an issue, I cant figure out what the problem is with the product controller error,
I will not render the product index view page which is what i want to work.
my code is here as follows :
offers controller
class OffersController < ApplicationController
attr_accessible :product , :reserve_price
def your_offer
#your_offer = Offer.new
end
def new
#offer = Offer.new = :your_offer
end
end
and Products Controller
class ProductsController < ApplicationController
before_filter :authenticate, :except => [:index, :show]
# GET /products
# GET /products.xml
def index
#offer = Offer.new
#products = Product.search(params[:search_query])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #products }
end
end
# GET /products/1
# GET /products/1.xml
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #product }
end
end
# GET /products/new
# GET /products/new.xml
def new
#product = Product.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #product }
end
end
# GET /products/1/edit
def edit
#product = Product.find(params[:id])
end
# POST /products
# POST /products.xml
def create
#product = current_user.products.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to(#product, :notice => 'Product was successfully created.') }
format.xml { render :xml => #product, :status => :created, :location => #product }
else
format.html { render :action => "new" }
format.xml { render :xml => #product.errors, :status => :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.xml
def update
#product = Product.find(params[:id])
respond_to do |format|
if #product.update_attributes(params[:product])
format.html { redirect_to(#product, :notice => 'Product was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #product.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.xml
def destroy
#product = Product.find(params[:id])
#product.destroy
respond_to do |format|
format.html { redirect_to(products_url) }
format.xml { head :ok }
end
end
end
Offer Model
class Offer < ActiveRecord::Base
belongs_to :product
has_many :reserve_prices
attr_accessible :product, :offer , :reserve_price
validates_presence_of :offer
validate :ensure_meets_reserve_price
private
def ensure_meets_reserve_price
if amount < self.product.reserve_price
errors.add(:amount, "does not meet reserve price")
end
end
private
def reserve_price
product.reserve_price
end
def your_offer
#your_offer = Offer.new
end
def new
#offer = Offer.new = :your_offer
end
end
product index viex snippet
<%= form_for #offer do |f| %>
<%= f.text_field :your_offer %>
<%= f.submit "Make Offer" %>
<% end %>
Could any one see where my eror is ?
Its complaining about #offer = Offer.new
Did you run the migration and restarted the server after creating offers?
Did you declare it as a resource in config/routes.rb as
resources :products, :shallow => true do
resources :offers # or at least just this line
end
Edit:
Get rid of this line and try again
attr_accessible :product, :offer , :reserve_price
is :offer a column in the offers table?
You cannot have columns from another model in attr_accessible.
I found how to render ActiveRecord objects in Rails 3, however I cannot figure out how to render any custom objects. I am writing an app without ActiveRecord. I tried doing something like this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
format.json { render :json => {'ok'=>true} }
end
end
When you specify a respond_to, then in your actions you would make a matching respond_with:
class AppControlls < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash)
end
end
It looks like you're conflating the old respond_to do |format| style blocks with the new respond_to, respond_with syntax. This edgerails.info post explains it nicely.
class AppController < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash.as_json)
end
end
You should never use to_json to create a representation, only to consume the representation.
format.json { render json: { ok: true } } should work
This was very close. However, it does not automatically convert the hash to json. This was the final result:
class AppControlls < ApplicationController
respond_to :json
def start
app.start
respond_with( { :ok => true }.to_json )
end
end
Thanks for the help.
For those getting a NoMethodError, try this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
render json: { :ok => true }
end
end