I am building a rails app and I need to be able to send json from an api endpoint for and android app im building.
I can currently get the json I need from a different controller but I am trying to condense all my api calls to one api controller.
my JBuilder file looks like this
json.array!(@rivers) do |river|
json.extract! river, :id, :name, :section, :difficulty, :cfs, :details, :state, :put_in, :take_out, :picture
json.has_alert has_alert? river
end
It is currently getting used from my rivers controller index action
def index
if !params[:commit].nil?
@rivers = search params
if @rivers.nil?
@rivers = []
end
else
@rivers = River.where(approved: true)
end
end
I have an identical copy of the JBuilder file to be used by the api river action
def rivers
river_list = search params
if river_list.nil?
river_list = []
end
end
I want to be able to render the custom json the the jbuilder file gets me. I have been able to render json from the api controller using
render json: river_list
But it gives me more information that I don't actually want. Is there anyway to render custom json without using the jbuilder. The important part is that i need a json array
If you want to render the specific jbuilder view file, you can call it like this
render json: "name_of_the_jbuilder_file"
So your rivers method would look like this
def rivers
river_list = search params
if river_list.nil?
river_list = []
end
render template: "jbuilder_filename"
end
Take note that your jbuilder file needs the instance varialbe @rivers
, but the rivers
method don't have the @rivers
instance variable so this would fail, you should instantiate the instance variable first to render the json successfully.
Edit
Sorry, please use render template: "jbuilder_filename"
instead of render json
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.