EDIT: Solved. Solution:
Include
gem 'rabl' and gem 'oj' in your gemfile along with gem rabl-rails
For some reason, my instance variable isn't being passed into the view (I'm using Rabl).
Here's the relevant code:
articles_controller.rb
class ArticlesController < ApplicationController
respond_to :json, :xml
def index
#articles = Article.original.last(100)
end
def after
#articles = Article.where("id > #{params[:id]}")
end
def show
#article = Article.find(params[:id])
end
end
show.json.rabl
object #article
attributes :id, :headline, :source, :link
attributes :similar_articles => :similar
The error:
RuntimeError in Articles#show
Showing /Users/chintanparikh/Dropbox/Projects/Current/article_aggregator/app/views/articles/show.json.rabl where line #2 raised:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Any ideas?
The ID you're using to look up the record does not match one within your database.
Check what params[:id] is evaluating to and ensure that you can locate a record using that value.
Found the solution, you need these three lines in your Gemfile:
gem 'rabl-rails'
gem 'rabl'
gem 'oj'
Before, I only had rabl-rails, and I assume that was causing the problem.
Related
I'm building a simple rails application where users can upload some images. Now I need a simple controller that returns the image's URLs of related record which have the same id_attivita. To do so I create a function in the controller and enable it in the routes.rb file.
My question is about how to respond to the http request with the attribute value of image.url provided from paperclip?
def getattached
#photo_attivitum = PhotoAttivitum.where(id_attivita: params[:id_attivita])
respond_to do |format|
#photo_attivitum.each do |p|
format.html { render :json => p.image.url}
end
end
end
it works but it returns only the URLs of the first record not the other four record's URLs...
How can I do this?
Add the following gem to your Gemfile
gem 'active_model_serializers'
Then install it using bundle
bundle install
You can generate a serializer as follows
rails g serializer photo_attivitum
it will create Serializer class file in
# app/serializers/photo_attivitum_serializer.rb
class PhotoAttivitumSerializer < ActiveModel::Serializer
attributes :id, :image_url
def image_url
object.image.url
end
end
And in controller
def getattached
#photo_attivitum = PhotoAttivitum.where(id_attivita:
params[:id_attivita])
render json: #photo_attivitum
end
Not sure what u want to do? Show all image urls in json?
urls = #photo_attivitum.pluck('image_url')
format.html { render :json => urls}
I am upgrading my Rails app from 4.1.1 to 5.1.4.
I am using roar-rails gem to parsing and rendering REST documents. I am facing some issues as responders gem has been extracted to separate gem.
respond_with has been moved to 'responders' gem.
My rails 4 code lookgs like this:
PostsController:
class PostsController < ApplicationController
respond_to :json
def index
posts = current_user.posts
respond_with posts, :represent_with => PostsRepresenter, current_user: current_user
end
end
My representers for Post
module PostsRepresenter
# Rails 4 code
# include Roar::Representer::JSON::HAL
# Rails 5 code (after adding responders) --------
include Roar::JSON
include Roar::Hypermedia
# Rails 5 code --------
collection(
:post,
class: Post,
extend: PostRepresenter,
embedded: true)
link :make do |args|
p "............. #{args.inspect}"
# In rails 4, args are coming correctly what is passing from Controller
# But in rails 5, args is coming `nil`
posts_path if args[:current_user].can_create?(Post)
end
end
Post representer
module PostRepresenter
# Rails 4 code
# include Roar::Representer::JSON::HAL
# Rails 5 code (after adding responders) --------
include Roar::JSON
include Roar::Hypermedia
# Rails 5 code --------
property :title
property :description
property :author
link :self do |args|
post_path(id) if args[:current_user].can_read?(self)
end
link :remove do |args|
post_path(id) if args[:current_user].can_delete?(self)
end
link :edit do |args|
post_path(id) if args[:current_user].can_update?(self)
end
end
I am facing issue with args which are passing through Controller,
after rails 5, its coming nil.
I have debug the issue and found that in responders gem, options are coming in respond_with method, but I think it could not send it to roar-rails.
/path-to-gem/vendor/responders-master/lib/action_controller/respond_with.rb
Here is snippet:
def respond_with(*resources, &block)
if self.class.mimes_for_respond_to.empty?
raise "In order to use respond_with, first you need to declare the " \
"formats your controller responds to in the class level."
end
mimes = collect_mimes_from_class_level
collector = ActionController::MimeResponds::Collector.new(mimes, request.variant)
block.call(collector) if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
options = resources.size == 1 ? {} : resources.extract_options!
options = options.clone
options[:default_response] = collector.response
p "====================== options :: #{options.inspect}"
# Options are correct till here but coming `nil` on representers
(options.delete(:responder) || self.class.responder).call(self, resources, options)
else
raise ActionController::UnknownFormat
end
end
Please let me know what needs to be done here that make args
available in representers
respond_with was deprecated from rails 4.2.1.
https://apidock.com/rails/ActionController/MimeResponds/respond_with
I have issue with gem acts-as-taggable-on in Rails 5 beta 3.
project.rb:
class Project < ActiveRecord::Base
acts_as_taggable
acts_as_taggable_on :skills
end
routes.rb
get 'tags/:skill', to: 'projects#index', as: :skill
projects_controller.rb:
class ProjectsController < ApplicationController
def index
if params[:category] && Category.exists?(params[:category])
#category = Category.find(params[:category])
#projects = #category.projects.order("projects.created_at DESC")
elsif params[:skill]
#projects = Project.tagged_with(params[:skill])
else
#projects = Project.all
end
#categories = Category.all
end
end
On line #projects = Project.tagged_with(params[:skill]) I get the following error:
ArgumentError: wrong number of arguments (given 2, expected 1) from
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.0.beta3/lib/active_record/sanitization.rb:8:in
`sanitize'
Looks like tagged_with is calling quote_value internally, which is an alias_method for sanitize.
sanitize expects only one argument, but the tagged_with is calling quote_value with two arguments, which is causing the issue.
Refer to acts_as_taggable, ActiveRecord::Sanitization and the
commit that introduced this change.
They fixed this. Download from the master branch, in your Gemfile:
gem 'acts-as-taggable-on', :github => 'mbleigh/acts-as-taggable-on', :branch => 'master'
I'm using the path helper methods to generate URLs in link_to, and they are returning URLs formated like this :
http://localhost:3000/tweets.4
when I was expecting them to be formated like this:
http://localhost:3000/tweets/4
Note how it is using a dot as the delimiter instead of the expected forward slash. The top link doesn't resolve to the correct view, it simply reloads the /tweets view. When I manually edit the URL to be like the bottom, it opens the correct /tweets/show/.
The closest thing I found in my online research was that people encountered this with wrongly nested routing statements - but I don't think I'm doing that here.
I would appreciate any help or pointers anyone can provide!
Here are the related source files and version information :
tweets/index.html.erb
<h1>Listing tweets</h1>
<% #tweets.each do |tweet| %>
<div>
<!-- creates path in format of /tweets.2 -->
<div><%= link_to tweet.status, tweets_path(tweet) %></div>
<!-- creates path in the format of /user.1 -->
<div><%= link_to tweet.user.name, users_path(tweet.user) %></div>
</div>
<% end %>
tweets_controller.rb
class TweetsController < ApplicationController
def index
#tweets = Tweet.all
end
def show
#tweet = Tweet.find(params[:id])
end
def new
#tweet = Tweet.new
end
def create
#tweet = Tweet.new(params[:tweet])
#tweet.user = User.last
if(#tweet.save)
redirect_to :root
end
end
def edit
#tweet = Tweet.find(params[:id])
end
def delete
end
end
routes.rb
Zombietweets::Application.routes.draw do
resources :tweets
root :to => 'tweets#index'
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.9'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
end
group :assets do
gem 'sass-rails', '3.2.3'
gem 'coffee-rails', '3.2.1'
gem 'uglifier', '1.0.3'
end
gem 'jquery-rails', '2.0.2'
I'm using Rails 3.2.9 and Ruby 1.9.3p327 (2012-11-10) [x86_64-darwin12.2.0]
Have you tried tweet_path and user_path ?
You want to access the show action. For that action, the model name must be singular in the *_path call.
To be sure, try a rake routes in a console.
EDIT:
You also forget to add resources :users in your routes file :)
I used 'uuidtools' gem in my controller this way:
def create
require 'uuidtools'
game = Game.new
game.permalink = Base64.encode64(UUIDTools::UUID.random_create)[0..8]
game.save
redirect_to :controller => 'home', :action => 'index'
end
I get this error about the requiring of 'uuidtools':
no such file to load -- uuidtools
(I added the gem to my gem file.)
How can I fix this?
Thanks,
Oded
Perhaps restarting the server would also had fixed the problem
Solved it.
What I did is to migrate the use of 'uuidtools' from the controller to the model:
class Game < ActiveRecord::Base
before_save :create_permalink
def create_permalink
self.permalink = Base64.encode64(UUIDTools::UUID.random_create)[0..8]
end
end
Did you run 'bundle install' to install the gem ?