ActiveAdmin sidebar didn't display any records - ruby

I am using a ActiveAdmin for building administration interface. So i have Articles and Products resources, in Article show i want to make a sidebar to see what products assigned to this Article. Sidebar is looks okey, but it doesn't display any records.
Rails 4.1.0
ActiveAdmin 1.0.0
ruby 2.1
app/admin/article.rb
ActiveAdmin.register Article, { :sort_order => :name_asc } do
# Permitted parameters
permit_params :title, :description
# Displayed columns
index do
selectable_column
column :title
column :description
default_actions
end
# Sidebar for Products by this Article
sidebar 'Products by this Article', :only => :show do
table_for Product.joins(:article).where(:article_id => article.id) do |s|
s.column("Title") { |product| product.title }
end
end
# Filters for title and description
filter :title, :as => :select # :check_boxes (for checkboxes)
filter :description, :as => :select
end
app/admin/product.rb
ActiveAdmin.register Product, { :sort_order => :name_asc } do
# Permitted parameters
permit_params :article_id, :title, :description, :price
# Displayed columns
index do
selectable_column
column :article, :sortable => :article
column :title
column :description
# Currency helper
column :price, :sortable => :price do |cur|
number_to_currency cur.price, locale: :ru
end
default_actions
end
# Filters for each column within "description"
filter :article, :as => :select # :check_boxes (for checkboxes)
filter :title, :as => :select
filter :price
end
app/models/article.rb
class Article < ActiveRecord::Base
# Relationship
has_many :products
# Validations
validates :title, :description, :presence => true
end
app/admin/models/product.rb
class Product < ActiveRecord::Base
# Relationship
belongs_to :article
# Validations
validates :article, :title, :description, :price, :presence => true
end

Related

Active admin nested form not working Error: too many arguments for format string

Following is my code block of state Model, SatatImage Model and Active Admin Code. In active admin when I try to create a new record or Edit a --record that time I show an error on production server. but works on my localhost in development mode,
---------Error---------------------------
too many arguments for format string
app/admin/state.rb:49:in `block (2 levels) in '
I am using Ruby 1.9, Rails 3,2, activeadmin (0.6.0)
======State Model===============
class State < ActiveRecord::Base
attr_accessible :name, :code
validates :code, :uniqueness => true
has_one :state_image, :dependent => :destroy
accepts_nested_attributes_for :state_image, :allow_destroy => true
.......
end
==============StatImage Model=============
class StateImage < ActiveRecord::Base
attr_accessible :state_id, :stateimage, :image_name
belongs_to :state
mount_uploader :stateimage, StateUploader
end
=======Active Admin part=================
ActiveAdmin.register State do
.....
form(html:{multipart:true}) do |f|
f.inputs "State Form" do
f.input :name, required:true
f.input :code, required:true
end
#line-49#
f.inputs "StateImage", for:[:state_image, f.object.state_image || StateImage.new] do |p|
p.input :stateimage, :as => :file, :label => "Image"
end
f.buttons :submit
end
end
I am using
f.semantic_fields_for
And Formtastic requires you to wrap ALL inputs in an "inputs" block. So this should be:
f.inputs 'State Image' do
f.semantic_fields_for :state_image, (f.object.state_image || StateImage.new) do |p|
p.inputs do
p.input :stateimage, :as => :file, :label => "Image"
p.input :_destroy, :as => :boolean, :required => false, :label => 'Remove image'
end
end
end
Please try this:
form :html => { :enctype => "multipart/form-data" } do |f|
Also upgrade you activeadmin version to 0.6.6

Ruby ActiveModel::MissingAttributeError

I'm trying to learn on my own ruby database relations.
I have a relation of 1 "Category" to many "Products" and I'm trying to add a product to the remote database (heroku server).
TIMESTAMP_create_products.rb
class CreateProducts < ActiveRecord::Migration
def up
create_table :products, primary_key: 'product_id' do |p|
p.index :product_id
p.string :name
p.decimal :price
p.references :categories, index: true
end
end
def down
drop_table :products
end
end
TIMETSTAMP_create_categories.rb
class CreateCategories < ActiveRecord::Migration
def up
create_table :categories, primary_key: 'category_id' do |c|
c.index :category_id
c.string :name
c.integer :parentId
end
end
def down
drop_table :categories
end
end
model.rb
class Products < ActiveRecord::Base
self.primary_key = "product_id"
validates :name, presence: true, uniqueness: true
belongs_to :categories, class_name: "Categories", foreign_key: 'category_id'
end
class Categories < ActiveRecord::Base
self.primary_key = "category_id"
validates :name, presence: true, uniqueness: true
has_many :products, class_name: "Products"
end
I add manually a category to the database and every time I try to execute the code:
Products.create(name: "name1", price: "1.1", categories: Categories.find(1))
It gives me the output:
ActiveModel::MissingAttributeError can't write unknown attribute category_id
Is there anything missing here? I don't understand why this is not working.
You may have a problem with singular / plural.
In your migration, to create the table products, you have the line:
p.references :categories, index: true
This should add to your table the column categories_id.
However, in the Products model, the foreign key is set to category_id. So when you try to attach a category to a production, it's trying to write the ID of the category to the column category_id of the table categories, which doesn't exists.
By changing the reference name in the products migration, everything should work fine:
create_table :products, primary_key: 'product_id' do |p|
p.index :product_id
p.string :name
p.decimal :price
p.references :category, index: true
end

ActiveAdmin calculations

I want to implement some calculation to my admin interface, so i have a product resource, at this resource you see a list of services that I do, such as airbrushing, price on application considered as, for example (1 $ per 1 square cm).
How i can better realize this idea?
I would like to see when a user pushing a button "New Product" it was a field where he writes the number of square centimeters and on the basis of these dimensions, it automatically render the required amount in the currency.
Rails 4.1.0
ActiveAdmin 1.0.0
ruby 2.1
Just now you can only type a fixed price, like fixed price for 1 product/service.
app/admin/product.rb
ActiveAdmin.register Product, { :sort_order => :name_asc } do
# Scopes
scope :all, :default => true
scope :available do |products|
products.where("available < ?", Date.today)
end
scope :drafts do |products|
products.where("available > ?", Date.today)
end
scope :featured_products do |products|
products.where(:featured => true)
end
# Permitted parameters
permit_params :article_id, :title, :description, :price, :featured, :available, :image_file_name
# Displayed columns
index do
selectable_column
column :article, :sortable => :article
column :title, :sortable => :title
column :description
# Currency helper
column :price, :sortable => :price do |cur|
number_to_currency cur.price, locale: :ru
end
column :featured
column :available
# column :image_file_name
actions
end
# Product details
show do
panel "Product Details" do
attributes_table_for product do
row("Article") { link_to product.article }
row("Title") { product.title }
row("Description") { product.description }
row("Price") { product.price }
row("Featured") { product.featured }
row("Available on") { product.available }
row("Image") { image_tag("products/" + product.image_file_name) }
end
end
end
# Filters
filter :article, :as => :select
filter :title, :as => :select # :check_boxes (for checkboxes)
filter :price, :as => :select
filter :available, :as => :select
filter :featured, :as => :check_boxes
end
app/models/product.rb
class Product < ActiveRecord::Base
# Relationship
belongs_to :article
# Named Scopes
scope :available, lambda{ where("available < ?", Date.today) }
scope :drafts, lambda{ where("available > ?", Date.today) }
# Validations
validates :article, :title, :description, :price, :available, :presence => true
validates :featured, :inclusion => { :in => [true, false] }
end
app/models/article.rb
class Article < ActiveRecord::Base
# Relationship
has_many :products, :dependent => :delete_all
# Validations
validates :title, :description, :presence => true
# Define for display a article for products as article code
def to_s
"#{title}"
end
end

Rails - has_many build method not saving association

I'm having some trouble trying to make association works.
My models looks like:
advertise.rb
class Advertise < ActiveRecord::Base
belongs_to :user
belongs_to :country
has_many :targets
# has_many :hss, :through => :targets
validates :description, :presence => true
validates :url, :presence => true
validates :country_id, :presence => true
validates :kind, :presence => true
attr_accessible :description, :hits, :url, :active, :country_id, :kind
KINDS = {
'1' => 'Commoditie',
'2' => 'Service',
}
HS = {
'1' => 'Section',
'2' => 'Chapter',
'4' => 'Heading',
'5' => 'SubHeading 1',
'6' => 'SubHeading 2',
}
end
hs.rb
class Hs < ActiveRecord::Base
attr_accessible :code, :kind
has_many :targets
has_many :advertises, :through => :targets
end
target.rb
class Target < ActiveRecord::Base
attr_accessible :advertise_id, :hs_id
belongs_to :advertise
belongs_to :hs
end
advertises_controller.rb
def new
#advertise = Advertise.new
#countries = Country.all
end
def create
#advertise = current_user.advertises.build(params[:advertise])
if #advertise.save
flash[:notice] = 'Advertise created with successful'
redirect_to root_path
else
render :new
end
end
the form for creating a new Ad.
/advertises/new.html.haml
%table.table.table-striped
%tr
%td{:colspan => 2}= advertise.input :url, :required => true
%tr
%td{:colspan => 2}= advertise.input :description, :required => true, :as => :text, :input_html => { :cols => 50, :rows => 3 }
%tr
%td{:colspan => 2}= advertise.input :country_id, :collection => #countries, :as => :select, :label => 'Origin', :required => true
%tr
%td{:colspan => 2}= advertise.input :kind, :collection => Advertise::KINDS.map(&:reverse), :as => :select, :label => 'Type', :required => true
%tr
%td{:colspan => 2}= advertise.input_field :active, as: :boolean, inline_label: 'Active'
=fields_for :targets do |target|
%tr
%td= select_tag :hs_kind, options_for_select(Advertise::HS.map(&:reverse).insert(0,'') )
%td= target.select :hs_id, ''
The hash params:
[3] pry(#<AdvertisesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"fOdn4NYLg/4HXruWURZPf9DYVT4EQzbaTRTKZvX1ugY=",
"advertise"=>
{"url"=>"http://test.com",
"description"=>"test",
"country_id"=>"17",
"kind"=>"2",
"active"=>"1"},
"hs_kind"=>"2",
"targets"=>{"hs_id"=>"487"},
"commit"=>"Create Advertise",
"action"=>"create",
"controller"=>"advertises"}
The hash seems ok to me, but it creates only the Advertise, and not creates the target for the advertise associated.
Any though? Maybe a wrong model association.
Thanks in advance.
try changing
=fields_for :targets do |target|
to
= advertise.fields_for :targets do |target|
and add the following to advertise.rb
accepts_nested_attributes_for :targets
attr_accessible :targets_attributes # just add targets_attributes to attr_accessible
be warned that when you do this, advertise objects that has no targets will not show the fields for targets. you have to build a new target object associated to advertise in order to show the fields
# example: on the new action of the controller
#advertise = Advertise.new
#advertise.targets.build

Why is assign_attributes with array of ids for has_many association only associating one object?

I have a form where users can upload assets using ajax. This creates many Asset objects that I then want to associate with a Post object when it is created. I have a form_field named asset_ids that I update with the created Asset ids as they are created. When I create the Post object and populate its data with assign_attributes, only ONE association is created, no matter how many ids are there.
Asset model:
class Asset < ActiveRecord::Base
attr_accessible :caption, :image
belongs_to :post
has_attached_file :image, :styles => { :large => "600x600>", :medium => "300x300>", :thumb => "100x100>" }
end
Post model:
class Post < ActiveRecord::Base
attr_accessible :content, :post_date, :status, :title, :tag_list, :asset_ids, :as => :admin
has_many :assets, :dependent => :destroy
has_and_belongs_to_many :tags
validates :content, :post_date, :title, :presence => true
end
An example of the posted data hash:
{"title"=>"Test post", "status"=>"true", "post_date"=>"01/02/2013", "content"=>" Some content", "tag_list"=>"", "asset_ids"=>"97,102"}
The example above assigns only one Asset (id 97) to the new Post, when I assign_attributes like so:
#post = Post.new
#post.assign_attributes params[:post], :as => :admin
I had to make sure I was assigning the ids as an array:
#post.asset_ids = params[:post][:asset_ids].split(",")

Resources