Using paperclip with factory girl, no image handler error - ruby-on-rails-3

I am trying to use paperclip with factory_girl gem but getting a "no handler found
error" message.
test_should_update_category(CategoriesControllerTest):
Paperclip::AdapterRegistry::NoHandlerError: No handler found for "/system/categories/images/000/000/001/original/tel1.JPG?1354197869"
Factory girl file:
FactoryGirl.define do
factory :category do
name "MyString"
description "MyText"
image { File.new(File.join(Rails.root, 'test','tel1.JPG')) }
end
end
category migration ::---------------
class CreateCategories < ActiveRecord::Migration
def up
create_table :categories do |t|
t.string :name
t.text :description
t.string :image
t.timestamps
end
add_attachment :categories, :image
end
model:
class Category < ActiveRecord::Base
attr_accessible :description, :image, :name
has_attached_file :image, :styles => { :thumb => "100x100>" }
end
category controller test file:
require 'test_helper'
class CategoriesControllerTest < ActionController::TestCase
setup do
#category = FactoryGirl.create(:category)
end

I make it to work with the following code in my app / factory:
FactoryGirl.define do
factory :upload do
permalink "unique"
upload Rack::Test::UploadedFile.new(Rails.root + 'spec/files/uploads/unique.jpg', 'image/jpg')
end
end
So in your app you should change your factory of category to something like this:
FactoryGirl.define do
factory :category do
name "MyString"
description "MyText"
image Rack::Test::UploadedFile.new(Rails.root +'test/tel1.JPG', 'image/jpg')
end
end

Related

Couldn't find <Model> with ID=14 for Property with ID=1

when update, i got error like this.
Couldn't find PropertyAcceptanceCriterion with ID=14 for Property with ID=1
this error occur when off the checkbox, and update(save).
what should i do next,
model definition is
class PropertyAcceptance < ActiveRecord::Base
belongs_to :property
belongs_to :property_acceptance_criterion
end
class PropertyAcceptanceCriterion < ActiveRecord::Base
attr_accessible :name
has_many :property_acceptances, dependent: :destroy
has_many :properties, through: :property_acceptances
end
class Property < ActiveRecord::Base
attr_accessible :rent
attr_accessible :room_no
attr_accessible :property_acceptance_criterions_attributes
attr_accessible :property_acceptance_criterion_ids
has_many :property_acceptances, dependent: :destroy
has_many :property_acceptance_criterions, through: :property_acceptances
accepts_nested_attributes_for :property_acceptance_criterions, reject_if: lambda { |a| a[:name].blank? }
end
view definition is
= simple_nested_form_for #property do |f|
= f.input :room_no, input_html: {class: 'span2'}
= f.input :rent, input_html: {class: 'span2'}
= f.association :property_acceptance_criterions, as: :check_boxes
= f.simple_fields_for :property_acceptance_criterions do |c|
= c.input :name, label: "add for #{t('activerecord.attributes.property.property_acceptance_criterions')}" if c.object.new_record?
controller definition is
class Insurance::PropertiesController < Insurance::InsuranceController
before_filter :load_property, only: [:edit, :update]
before_filter :new_property, only: [:new, :create]
def new
#property.property_acceptance_criterions.build
end
def create
#property.attributes = params[:property]
if #property.save
redirect_to #property, success: t('activerecord.flash.property.actions.create.success')
else
render :new
end
end
def edit
#property.property_acceptance_criterions.build
end
def update
if #property.update_attributes(params[:property]) # ← error occur
redirect_to #property, success: t('activerecord.flash.property.actions.update.success')
else
render :edit
end
end
private
def load_property
#property = Property.find(params[:id])
end
def new_property
#property = Property.new
end
end
error is
Couldn't find PropertyAcceptanceCriterion with ID=14 for Property with ID=1
params is
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"+Zx7l7mAbX12PSO873x5NDxNOIeEe6bEDEdVnys+a98=",
"property"=>{
"room_no"=>"000",
"rent"=>"80000",
"property_acceptance_criterion_ids"=>["13", "25", ""],
"property_acceptance_criterions_attributes"=>{
"0"=>{"id"=>"13"}, "1"=>{"id"=>"14"}, "2"=>{"id"=>"25"}, "3"=>{"name"=>""}
},
"commit"=>"update",
"id"=>"1"}

Ruby on Rails Has_Many :Through Association

I'm having some problems with ruby on rails, specifically setting up a many-to-many connection with deal and event through deal_event. I've checked out several similar stackoverflow questions and even http://guides.rubyonrails.org/ but I'm still not getting something..
Here are my models:
deal.rb
class Deal < ActiveRecord::Base
has_many :deal_events
has_many :events, :through => "deal_events"
attr_accessible :approved, :available, :cents_amount, :dollar_amount, :participants, :type
end
event.rb
class Event < ActiveRecord::Base
has_many :deal_events
has_many :deals, :through => "deal_events"
attr_accessible :day, :image, :description, :location, :title, :venue, :remove_image
end
deal_event.rb
class DealEvent < ActiveRecord::Base
belongs_to :deal
belongs_to :event
end
And here are my migration files:
20130102150011_create_events.rb
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :title, :null => false
t.string :venue
t.string :location
t.text :description
t.date :day
t.timestamps
end
end
end
20130112182824_create_deals.rb
class CreateDeals < ActiveRecord::Migration
def change
create_table :deals do |t|
t.integer :dollar_amount
t.integer :cents_amount
t.integer :participants
t.string :type, :default => "Deal"
t.integer :available
t.string :approved
t.timestamps
end
end
end
20130114222309_create_deal_events.rb
class CreateDealEvents < ActiveRecord::Migration
def change
create_table :deal_events do |t|
t.integer :deal_id, :null => false
t.integer :event_id, :null => false
t.timestamps
end
end
end
After I seed my database with one deal and one event, I go into the console and type in
deal = Deal.first # ok
event = Event.first # ok
DealEvent.create(:deal => deal, :event => event) # Error: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: deal, event
deal.events # Error: ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association "deal_events" in model Deal
Any idea on what I'm doing wrong for these two errors to be popping up? Thanks.
You'll need this line in your DealEvent model:
attr_accessible :deal, :event
Although if it's just a relationship table (which it looks like) then you don't create the relationship that way. Use nested forms and the like.

self.votable not assigning values to the votable instance in a model callback?

I have a Post model that has a polymorphic association with a Vote model:
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :total_votes
belongs_to :user
has_many :votes, :as => :votable, :dependent => :destroy
end
vote.rb
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
end
end
As you can see in vote.rb I want to accomplish the following:
Each time an instance of Vote is created, I want to update the total_votes column of the votable model instance (in this case an instance of Post).
But nothing happens, when I create a vote for a post with post.votes.create(:polarity => 1), the total_votes column of the post still being nil.
Any suggestions to fix this?
EDIT:
This didn't work either:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
self.votable.save!
end
end
schema.rb:
create_table "posts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "title"
t.integer "comments_count", :default => 0, :null => false
t.integer "total_votes"
end
When you create the Vote object, the Post object already exists. You update it, but you don't save it. Try with the following code:
def update_total
self.votable.total_votes ||= 0
self.votable.total_votes += self.polarity
self.votable.save!
end

Polymorphic :has_many, :through as module in Rails 3.1 plugin

I've search everywhere for a pointer to this, but can't find one. Basically, I want to do what everyone else wants to do when they create a polymorphic relationship in a :has_many, :through way… but I want to do it in a module. I keep getting stuck and think I must be overlooking something simple.
To wit:
module ActsPermissive
module PermissiveUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_permissive
has_many :ownables
has_many :owned_circles, :through => :ownables
end
end
end
class PermissiveCircle < ActiveRecord::Base
belongs_to :ownable, :polymorphic => true
end
end
With a migration that looks like this:
create_table :permissive_circles do |t|
t.string :ownable_type
t.integer :ownable_id
t.timestamps
end
The idea, of course, is that whatever loads acts_permissive will be able to have a list of circles that it owns.
For simple tests, I have
it "should have a list of circles" do
user = Factory :user
user.owned_circles.should be_an_instance_of Array
end
which fails with:
Failure/Error: #user.circles.should be_an_instance_of Array
NameError: uninitialized constant User::Ownable
I've tried: using :class_name => 'ActsPermissive::PermissiveCircle' on the has_many :ownables line, which fails with:
Failure/Error: #user.circles.should be_an_instance_of Array
ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source association(s) :owned_circle or
:owned_circles in model ActsPermissive::PermissiveCircle.
Try 'has_many :owned_circles, :through => :ownables,
:source => <name>'. Is it one of :ownable?
while following the suggestion and setting :source => :ownable fails with
Failure/Error: #user.circles.should be_an_instance_of Array
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:
Cannot have a has_many :through association 'User#owned_circles'
on the polymorphic object 'Ownable#ownable'
Which seems to suggest that doing things with a non-polymorphic-through is necessary. So I added a circle_owner class similar to the setup here:
module ActsPermissive
class CircleOwner < ActiveRecord::Base
belongs_to :permissive_circle
belongs_to :ownable, :polymorphic => true
end
module PermissiveUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_permissive
has_many :circle_owners, :as => :ownable
has_many :circles, :through => :circle_owners,
:source => :ownable,
:class_name => 'ActsPermissive::PermissiveCircle'
end
end
class PermissiveCircle < ActiveRecord::Base
has_many :circle_owners
end
end
With a migration:
create_table :permissive_circles do |t|
t.string :name
t.string :guid
t.timestamps
end
create_table :circle_owner do |t|
t.string :ownable_type
t.string :ownable_id
t.integer :permissive_circle_id
end
which still fails with:
Failure/Error: #user.circles.should be_an_instance_of Array
NameError:
uninitialized constant User::CircleOwner
Which brings us back to the beginning.
How can I do what seems to be a rather common polymorphic :has_many, :through on a module?
Alternatively, is there a good way to allow an object to be collected by arbitrary objects in a similar way that will work with a module?
It turns out that adding :class_name to both :has_many definitions will actually work (someone commented on that, but they deleted their comment). It didn't work in my non-simplified program because of something else in my program that was causing a cascading error that SEEMED to be local to the :has_many definition.
Short story: It was a lot of trouble for something that wasn't actually a problem. Blech

Using Rails Gem Active Admin with Associations

I'm trying out the new Rails gem http://activeadmin.info/ and it's working great! However I can't find any documentation on how to use it across associations. For example:
class Membership < ActiveRecord::Base
belongs_to :course
belongs_to :person
class Course < ActiveRecord::Base
has_many :memberships
has_many :people, :through => :memberships
class Person < ActiveRecord::Base
has_many :memberships
has_many :courses, :through => :memberships
The membership join table includes some extra data as well (ie: attendance). I'm trying to show the membership with both the course and student name - and allow filtering / sorting on those names. As far as I have found, Active Admin doesn't work across associations. Has anyone else been successful in doing that, or found another gem that does? Thanks so much!
ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :ingredients_products
end
product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :ingredients, :join_table => :ingredients_products
end
don't forget the migrations for the joining table (:id to false!)
class CreateProductsIngredients < ActiveRecord::Migration
def self.up
create_table :ingredients_products,:id => false do |t|
t.integer :product_id
t.integer :ingredient_id
t.timestamps
end
end
def self.down
drop_table :products_ingredients
end
end
Now define the form in you ActiveAdmin resource, override the default
ActiveAdmin.register Product do
form do |f|
f.inputs "Details" do
f.input :product_name
f.input :brand
f.input :ingredients # don't forget this one!
end
end
I've been playing with ActiveAdmin for a while now, here's how I managed to get associations to work in Indexes and Forms.
I've just guessed some of your model columns below. Also note, in the form. The 'person' section will show all the columns for editing, whereas the 'course' section will just show the specified column.
ActiveAdmin.register User do
index do
column :id
column :name
column :attendance
column :person do |membership|
membership.person.name
end
column :course do |membership|
membership.course.name
end
default_actions
end
form do |f|
f.inputs "Membership" do
f.input :name
f.input :created_at
f.input :updated_at
end
f.inputs :name => "Person", :for => :person do |person|
person.inputs
end
f.inputs :name => "Course", :for => :course do |course|
course.input :name
end
f.buttons
end
end
I haven't tested this, but you should be able to apply these ideas to your case. It's working for mine.
Update: I've just read your question again and noted that you're wanting to be able to sort on the association column. I've just checked my implementation and this indeed is not working. My answer may be useless to you but I'll leave it here anyway (might help someone else).
I've just started using this gem myself, and while I haven't gotten around to showing association information, here's how you create a form for associations:
form do |f|
f.inputs
f.has_many :associations do |association|
association.inputs
end
f.buttons
end
That will give you a basic form with scaffolding.
ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :ingredients_products
end
product.rb
class Product < ActiveRecord::Base
attr_accessible ingredient_ids
has_and_belongs_to_many :ingredients, :join_table => :ingredients_products
end
migration_xxx.rb
class CreateProductsIngredients < ActiveRecord::Migration
def self.up
create_table :ingredients_products,:id => false do |t|
t.integer :product_id
t.integer :ingredient_id
t.timestamps
end
end
def self.down
drop_table :products_ingredients
end
end
products.rb
ActiveAdmin.register Product do
form do |f|
f.inputs "Details" do
f.input :product_name
f.input :brand
f.input :ingredients
end
end
...
end