I wrote many simple rake files to import txt files to my mysql.
Everything work perfectly except one model.
I have no errors so I don't know what happening.
The rake imports the first line only. Everything else don't!
The txt is on UTF8 encoding, by the way.
Could be the counter_cache of recipe's associations?
RAILS 3.1
Model:
class Recipe < ActiveRecord::Base
belongs_to :chef, :counter_cache => true
belongs_to :category, :counter_cache => true
belongs_to :cuisine, :counter_cache => true
belongs_to :festivity, :counter_cache => true
belongs_to :daily, :counter_cache => true
after_update :update_counter
# Setup accessible (or protected) attributes for your model
attr_accessible :name,
:slug,
:description,
:ingredients,
:steps,
:...
:status_id,
:created_at,
:updated_at
STATUS = { 'Não publicada' => 0, 'Publicada' => 1, 'Invisível' => 4 }
def status
STATUS.invert[status_id]
end
private
def update_counter
if category_id_changed?
Category.increment_counter(:recipes_count, category_id)
Category.decrement_counter(:recipes_count, category_id_was)
end
if cuisine_id_changed?
Cuisine.increment_counter(:recipes_count, cuisine_id)
Cuisine.decrement_counter(:recipes_count, cuisine_id_was)
end
if festivity_id_changed?
Festivity.increment_counter(:recipes_count, festivity_id)
Festivity.decrement_counter(:recipes_count, festivity_id_was)
end
if daily_id_changed?
Daily.increment_counter(:recipes_count, daily_id)
Daily.decrement_counter(:recipes_count, daily_id_was)
end
end
end
RAKE file:
namespace :db do
desc "import data from files to database"
task :import_recipe => :environment do
puts "Importing Recipe..."
# recipe.txt
File.open("lib/tasks/data/recipe.txt", "r").each do |line|
id, name, slug, description, ingredients, steps, other_tips, cook_time, recipe_yield, diet, light, lactose_intolerance, vegetarian, microwave, video_url, chef_id, category_id, cuisine_id, festivity_id, daily_id, likes_count, rating, ratings_count, views_count, comments_count, status_id, created_at, updated_at = line.strip.split("\t")
d = Recipe.new(
:id => id,
:name => name,
:slug => slug,
:description => description,
:ingredients => ingredients,
:steps => steps,
:...
:status_id => status_id,
:created_at => created_at,
:updated_at => updated_at
)
d.save!
end
puts "=========== > FINISHED!"
end
end
Related
I'm trying to update an old Redmine plugin but when I try to do the migration I get this error. Could someone give me some pointers how to address the problem?
I tried to replace find_options with scope but I'm not exactly sure how do to it.
rake aborted!
ArgumentError: Unknown key: :find_options. Valid keys are: :type, :permission, :timestamp, :author_key, :scope
/home/developer/projects/redmine/redmine-3.3.1/lib/plugins/acts_as_activity_provider/lib/acts_as_activity_provider.rb:32:in `acts_as_activity_provider'
Migration file:
require File.join(File.dirname(__FILE__), '../../app/models', 'hudson_build')
class UpdateBuilding < ActiveRecord::Migration
def self.up
HudsonBuild.update_all "building = 'true'", "building = 't'"
HudsonBuild.update_all "building = 'false'", "building = 'f'"
end
def self.down
HudsonBuild.update_all "building = 't'", "building = 'true'"
HudsonBuild.update_all "building = 'f'", "building = 'false'"
end
end
part of my hudson_build.rb model that's causing the problem:
require 'hudson_api_error'
require 'hudson_exceptions'
require 'rexml_helper'
include RexmlHelper
class HudsonBuild < ActiveRecord::Base
unloadable
has_many :changesets, :class_name => 'HudsonBuildChangeset', :dependent => :destroy
has_one :test_result, :class_name => 'HudsonBuildTestResult', :dependent => :destroy
has_many :artifacts, :class_name => 'HudsonBuildArtifact', :dependent => :destroy
belongs_to :job, :class_name => 'HudsonJob', :foreign_key => 'hudson_job_id'
belongs_to :author, :class_name => 'User', :foreign_key => 'caused_by'
validates_presence_of :hudson_job_id, :number
validates_uniqueness_of :number, :scope => :hudson_job_id
acts_as_event :title => Proc.new {|o|
retval = "#{l(:label_build)} #{o.job.name} #{o.number}: #{o.result}" unless o.building?
retval = "#{l(:label_build)} #{o.job.name} #{o.number}: #{l(:notice_building)}" if o.building?
retval
},
:description => Proc.new{|o|
items = []
items << o.test_result.description_for_activity if o.test_result != nil
items << HudsonBuildChangeset.description_for_activity(o.changesets) if o.changesets.length > 0
items.join("; ")
},
:datetime => :finished_at
acts_as_activity_provider :type => 'hudson',
:timestamp => "#{HudsonBuild.table_name}.finished_at",
:author_key => "#{HudsonBuild.table_name}.caused_by",
:find_options => {:include => {:job => :project}},
:permission => :view_hudson
include HudsonHelper
extend RexmlHelper
I don't know this plugin but i found this commit
Please try changing in HudsonBuild class this line:
:find_options => {:include => {:job => :project}},
to
:scope => includes(:project),
Here is an example.
I dont know what I did or what's changed because this was working before.
I have a Model Entry and I use Paperclip to attach a file document to it. Now, for some weird reason I keep getting a
Errno::ENOENT in EntriesController#create
No such file or directory - /var/www/capsf-web/public/assets/entries/test.pdf
I'm guessing that before Paperclip has saved the file to the directory I'm already trying to encode the file. Here's what Entry looks like. I'm using ElasticSearch's attachment mapper which is why I Encode it.
class Entry < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
has_and_belongs_to_many :categories
has_and_belongs_to_many :subcategories
belongs_to :entry_type
has_attached_file :document,
:url => "/assets/entries/:basename.:extension",
:path => ":rails_root/public/assets/entries/:basename.:extension"
before_post_process :image?
validates_presence_of :entry_type
attr_accessible :description, :title, :url, :category_ids, :subcategory_ids, :entry_type_id, :document
mapping do
indexes :title
indexes :description
indexes :categories do
indexes :name
end
indexes :subcategories do
indexes :name
end
indexes :entry_type
indexes :document, :type => 'attachment'
end
def to_indexed_json
#to_json( methods: [:category_name, :subcategory_name, :entry_type_name])
{
:title => title,
:description => description,
:categories => categories.map { |c| { :name => c.name}},
:subcategories => subcategories.map { |s| { :name => s.name}},
:entry_type => entry_type_name,
:document => attachment
}.to_json
end
def image?
!(document_content_type =~ /^image.*/).nil?
end
def attachment
if document.present?
path_to_document = Rails.public_path+"/assets/entries/#{document_file_name}"
Base64.encode64(open(path_to_document) { |pdf| pdf.read})
#If I comment out the line above everything works just fine.
end
end
end
I'm developing an ActiveAdmin app, and I want to sort a column of businesses by their "type". Unfortunately my code is not working. What code should I use to accomplish this? Here is my code...
app/models/business.rb
class Business < ActiveRecord::Base
belongs_to :type
attr_accessible :description, :email, :facebook, :foursquare, :google, :manager,
:mobile, :name, :phone, :type_id, :url, :yelp
end
app/models/type.rb
class Type < ActiveRecord::Base
attr_accessible :category
has_many :businesses
def to_s
category
end
end
app/admin/businesses.rb
ActiveAdmin.register Business, { :sort_order => :name_asc } do
scope :joined, :default => true do |businesses|
businesses.includes [:type]
end
index do
column :name
column :type, :sortable => 'businesses.type'
column :manager
column :email
default_actions
end
end
Thanks!
according to this discussion: https://github.com/gregbell/active_admin/pull/623, if you don't want to use scopes, you can use the scoped collection method instead:
ActiveAdmin.register Business, { :sort_order => :name_asc } do
scope :all, :default => true
index do
column :name
column :type, :sortable => 'types.category'
column :manager
column :email
default_actions
end
controller do
def scoped_collection
end_of_association_chain.includes(:type)
end
end
end
FIXED
column :type, :sortable => 'types.category'
Yes, the scoped_collection Evgenia provided works great. Also for more than one columns:
ActiveAdmin.register Foo do
index do
column :field_name_a, :sortable => 'association_a.field_name'
column :field_name_b, :sortable => 'association_b.field_name'
end
end
controller do
def scoped_collection
end_of_association_chain.includes([:association_a, :association_b])
end
end
This can be done.
Here I have a model called Star. A star belongs to a Person. I'm going to put the Person.name in the Star admin index, make it sortable, make it work with scopes, and add filters.
First you have to add the join model to each of your scopes. In this case I had 3 scopes: all, category_subscriptions and person_subscriptions. I'm declaring the scopes and adding the join model to them:
ActiveAdmin.register Star do
[ :all, :category_subscriptions, :person_subscriptions ].each do |sym|
scope(sym, :default => (sym == :all) ) do |stars|
stars.includes [:person]
end
end
end
Now to add the person name from the join model into my star index I do this:
index do
id_column
column("Name", nil, :sortable => :"people.name") {|star| star.person.name}
column("Email", nil, :sortable => :"people.email") {|star| star.person.email}
default_actions
end
Let's dissect that:
column("Name", nil, :sortable => :"people.name") {|star| star.person.name}
The first parameter is the column title.
The second is not needed since we're overriding sort and the value.
:sortable tells Active Admin how to sort the thing. This is the table name, since it's going into SQL.
The block tells Active Admin what to use as a row value.
Now to add some filters. This is much easier:
filter :person_name, :as => :string
filter :person_email, :as => :string
And you're done.
Based on your needs this is my implementation working for sorting, default index and filtering:
ActiveAdmin.register Business do
index do
column :name
column :type, :sortable => 'businesses.type'
column :manager
column :email
default_actions
end
controller do
def scoped_collection
super.includes(:businesses)
end
end
end
Just in case you are wondering how to sort when you have one more level of the association, this is the way I'm dealing with that for eg:
class TechResult < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
belongs_to :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
and then in your tech_results section, you want to render an organization field, in my case the value tech_result.user.organization.name this is the way to sort them out:
ActiveAdmin.register TechResult do
config.batch_actions = false
permit_params :user_id
preserve_default_filters!
index do
column :id
column 'user', sortable: 'users.name' do |tr|
tr.user.name
end
column 'organization', nil, sortable: 'organizations.name' do |tr|
tr.user.organization.name.titleize if tr.user.organization
end
end
controller do
def scoped_collection
super.includes(user: [:organization])
end
end
end
class OrganizationModuleAttachment < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
end
class Document < ActiveRecord::Base
has_many :organization_module_attachments, :as => :attachable, :dependent => :destroy
def organization_module_attachment_ids=(values)
(values || []).each_with_index do |organization_module_id, index|
organization_module_attachments.build(:organization_module_id => organization_module_id, :attachable_type => "Document", :position => index + 1)
end
end
end
form.html.haml:
= f.select :organization_module_attachment_ids, options_for_select((#organization_modules || []).collect { |a| [a.name, a.id] }, (#document.organization_modules || []).collect { |a| a.id }), {}, { :class => "multiselect", :multiple => true }
So in the document class I am trying to build organization_module_attachments. I get an error in the creation of the organization module attachment when I submit the form. I think rails is assuming the foreign key on an attachment is :document_id, when in fact it is polymorphic and is therefore :attachable_id. If I explicitly set the :attachable_id in the build method it works fine.
I've tried a number of things and searched around for a few days with no luck. Does anyone know how to do this?
I have a simple one-to-many relationship between user and micropost as below. I tried to add a new column called stage to the Micropost model. when I try to build a new Micropost and save, the stage column is always automatically set to nil. I have tried create, build - doesn't matter, the stage field is always set to nil. I am baffled, please help!
$ rails console
Loading development environment (Rails 3.0.5)
>> User.first.microposts.create!( :stage => "p", :content => "test 6" )
=> #<Micropost id: 2, content: "test 6", stage: nil, user_id: 1, created_at: "2011-04-23 22:14:20", updated_at: "2011-04-23 22:14:20">
...
class Micropost < ActiveRecord::Base
attr_accessible :content, :stage
attr_accessor :stage
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
def self.followed_by(user)
followed_ids = %( SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where "user_id IN (#{followed_ids}) OR user_id = :user_id",
{ :user_id => user }
end
end
...
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
has_many :microposts, :dependent => :destroy
end
You need to remove line:
attr_accessor :stage
Without it everything works fine. I think it's conflict between attr_accessor and attr_accessible.