ruby-on-rails-4,paperclip,activeadmin,nested-forms , ActiveAdmin Papperclip Show multiple images in Index and show


ActiveAdmin Papperclip Show multiple images in Index and show

Question:

Tag: ruby-on-rails-4,paperclip,activeadmin,nested-forms

Hi just a quick Question on showing multiple images on the index-page and show page. My images are stored fine in a product_images table with a product_id as the foreign key.

Just going around in circles now on this. I've tried to play with similar code to no avail.

 row "Images" do
        ul do
          product.images.each do |img|
            li do
              image_tag(img.image.url(:small))
            end
          end
        end
      end

ActiveAdmin.register Product do

  # See permitted parameters documentation:
  # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
  #
   permit_params :id, :product_name, :product_description, :product_type_id, :product_category_id, :product_colour_id, :product_size_id,
                             product_images_attributes: [:id, :product_id, :product_image, :_destroy ]
  #
  # or
  #
  # permit_params do
  #   permitted = [:permitted, :attributes]
  #   permitted << :other if resource.something?
  #   permitted
  # end

  index do
          column :id
          column :product_name
          column :product_description

    actions
  end

   form(:html => {:multipart => true}) do |f|
     f.inputs "Product Details" do
       f.input :id
       f.input :product_name
       f.input :product_description

       f.inputs "Product images" do
         f.has_many :product_images do |p|
           p.input :product_image, :as => :file, :label => "Image",:hint => image_tag(p.object.product_image.url(:thumb))
           p.input :_destroy, :as=>:boolean, :required => false, :label => 'Remove image'
         end
       end
        f.actions
   end
end


  show title: :product_name do

    attributes_table do
      # other rows
      row :id
      row :product_name
      row :product_description

      end
  end

end

SOLUTION More playing and I fixed it

index do
      column :id
      column :product_name
      column :product_description
      column "Images" do |m|
        m.product_images.each do |img|
          span do
            image_tag(img.product_image.url(:thumb))
          end
        end
      end
      actions
 end

 show title: :product_name do

attributes_table do
  # other rows
  row :id
  row :product_name
  row :product_description
      row "Images" do |m|
        m.product_images.each do |img|
          span do
           image_tag(img.product_image.url(:thumb))
         end
        end
       end
      end
  end

Answer:

index do
      column :id
      column :product_name
      column :product_description
      column "Images" do |m|
        m.product_images.each do |img|
          span do
            image_tag(img.product_image.url(:thumb))
          end
        end
      end
      actions
 end

 show title: :product_name do

attributes_table do
  # other rows
  row :id
  row :product_name
  row :product_description
      row "Images" do |m|
        m.product_images.each do |img|
          span do
           image_tag(img.product_image.url(:thumb))
         end
        end
       end
      end
  end


Related:


Can't update existing records in Rails app


ruby,ruby-on-rails-4,simple-form
It appears that everything saves properly on my Rails 4 app (using simple_form) when I create a new event, but when I try to update an existing event (by going to events/3/edit), it doesn't save any of the changes. Here is my console log: Started PATCH "/events/3" for 12.43.117.2 at...

Rails, default.js is empty, and jquery and jquery_ujs not loaded


jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems
I am practicing ruby on rails by using rails guides. In the section 5.13 Deleting Articles they are showing how to create the delete (destroy) functionality. I followed the steps correctly, but the delete confirmation dialogue isn't shown and the articles are not getting deleted. When I checked the chrome...

Rails - How to find tilt version?


ruby-on-rails-3,ruby-on-rails-4,sprockets,tilt
Gem tilt is used with sprockets for Rails assets precompile. We are having hard time to find the version running on our Rails 4 app as tilt --version returns version unknown: $ tilt --version tilt: version unknown tilt --help give no info about how to find version. Is there way...

Rails Association Guidance [on hold]


ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2
I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

adding link_to with image_tag and image path both


html,ruby-on-rails,image,ruby-on-rails-4,svg
I am trying to replace the tag with link_to in my rails application view. for replacing I have svg icon, text and link all in one tag. Here is below <a class="navbar-brand" href="index.html"><%= image_tag 'logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;" %> My Project </a> but I...

How to avoid duplicates from saving in database parsed from external JSON file with sidekiq in Rails


ruby-on-rails,json,ruby-on-rails-4,sidekiq
I have a small To Do list in a .json file that I´m reading, parsing, and saving to a rails app with Sidekiq. Everytime I refresh the browser, the worker executes and duplicates the entries on the database. How do I maintain a unique database that is synchronized with the...

Rails 4 - Javascript - trouble with .not()


javascript,jquery,html,ruby-on-rails,ruby-on-rails-4
Can someone tell me what is wrong in this Javascript ? It's supposed to show an alert "already opened" if there's plus (or) 2 PP div with a class "open". if ($('PP').not('.closed')>=2) { window.alert('already opened'); } ...

How to validate in database for uniqueness?


ruby-on-rails,validation,ruby-on-rails-4
I am using Rails 4.2 with Ruby 2.1.5. Here is my API table: create_table "apis", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.string "status" t.string "coname" end How do I validate that a user cannot create an API with the same name and same status twice? For...

Order of including Helpers in ViewControllers


ruby,ruby-on-rails-4,method-overriding
In rails app, how are helpers included in viewcontrollers, and what's the order of includion(which helper is included first, second, so on)? Also, are all helpers available to views? If so, does the inclusion order same as the view's corresponding controller?...

Rails 4 wicked_pdf generate blank pdf while generating from model


ruby-on-rails-4,wicked-pdf
I'm trying to save pdf on server using rails model buts its generate a blank pdf. Earlier did it in controller without problem but now its creating a blank one. Any idea What's i did wrong? def generate_bulk_pdf view = ActionView::Base.new(ActionController::Base.view_paths, {}) view.extend(ApplicationHelper) view.extend(AbstractController::Rendering) view.extend(Rails.application.routes.url_helpers) students = Student.all.order('id ASC') students.each...

Controller method: Contact form should render different page depending on where the form is used


ruby-on-rails,ruby,forms,ruby-on-rails-4,controller
I have a contact form on a special page dedicated to this form. The dedicated controller includes: def new @message = Message.new end def create @message = Message.new(message_params) if @message.valid? MessageMailer.new_message(@message).deliver_now flash[:success] = "Thank you!" redirect_to contact_path else render 'new' end end Now I would also like to include this...

How do I setup a multi-option voting system using acts-as-votable?


ruby-on-rails,ruby-on-rails-4
I want to use acts-as-votable to implement a voting system where I can supply multiple custom options - e.g. 5 buttons ('blue', 'red', 'green', 'grey', 'white'). I want my users to be able to choose only 1 of those colors, but I would like to be able to tally up...

Get X days out of an Array


ruby,ruby-on-rails-4
I have an array filled with Datetime objects: [Mon, 22 Jun 2015, Tue, 23 Jun 2015, Wed, 24 Jun 2015, Thu, 25 Jun 2015, Fri, 26 Jun 2015, Sat, 27 Jun 2015, Sun, 28 Jun 2015] I know how to select what I want from the array ex: week.select{|x|x.monday? ||...

Redirect Loop on Heroku with Rails 4 App, but not on local machine


ruby-on-rails,ruby-on-rails-4,heroku,dns
App running Ruby 2.2.2, Rails 4.2.1 When I run my app locally everything is fine. It was running fine on heroku until I made some updates. Now all I get in a browser is "Err too many redirects" from Chrome, or "Too many redirects..." in Safari. Even after I rolled...

rails - NameError (undefined local variable or method while using has_many :through


ruby-on-rails,ruby,ruby-on-rails-4
My rails app gives following error: NameError (undefined local variable or method 'fac_allocs' for #): app/models/room.rb:4:in '' app/models/room.rb:1:in '' app/controllers/rooms_controller.rb:3:in 'index' room.rb file class Room < ActiveRecord::Base has_many :bookings has_many :fac_allocs has_many :facs, :through => fac_allocs end ...

Styling navbar: interaction between different styling settings


html,css,ruby-on-rails,ruby-on-rails-4
I'm having problems with styling my navigation bar, specifally the drop-down menu within the navigation bar. The two li elements below (the ones linking to "Profile" and "Edit profile" don't show up right. As you can see I have added the class my-dropdown-item in two different manners, both with the...

adding background image in style rails 4


ruby-on-rails,twitter-bootstrap,ruby-on-rails-4,asset-pipeline
I am trying to add background image on my web page, it was working when I was using plane html, but now I am integrating it to my rails application. I am using this code to embed the image in my rails application <div class="jumbotron" style="background-image: "url(image-url('lines3.png')"; background-repeat: repeat-x; background-position:...

Where is the defination of rails validators?


oop,ruby-on-rails-4
I am a beginner in rails. As I was working on rails validation, I wanted to know where is the definition of valid? and new_record? and all the validation helpers? I was trying to find the definition of all these functions but couldn't find any. Where do all this validations...

Redirect to edit page automatically if record exists


ruby-on-rails,ruby-on-rails-4,redirect
I want to create a new record if it not exist. Otherwise, redirect to edit page automatically. In case the record exists (e.g: @sale is not nil). However, I got error message: app/views/sales/_form.html.erb where line #1 raised: First argument in form cannot contain nil or be empty Please show place...

Multiple many-to-many association between two models


ruby-on-rails-4,activerecord,associations
I've created a many to many relation ship like the following structure. Class User has_many :companies, :through => company_admins has_many :company_admins end Class Company has_many :company_admins has_many :users, :through => company_admins end Class CompanyAdmin belongs_to :company belongs_to :user end Here, User can be assigned as admin on many Company. Now...

Error when trying to install app with mysql2 gem


mysql,ruby-on-rails,ruby,ruby-on-rails-4
Im trying to install an open source rails 3.2.21 application that uses the mysql2 gem, but when i try and run the bundle commant I get the following error: Fetching: mysql2-0.3.18.gem (100%) Building native extensions. This could take a while... p ERROR: Error installing mysql2: ERROR: Failed to build gem...

Rails add hash into existing hash


ruby,ruby-on-rails-4
I would like to do smth like: a = Hash.new a = {:profile => @user} a[:profile][:contacts] = Hash.new a[:profile][:contacts] = @user.contacts.all but I am getting the error can't write unknown attribute `contacts'. @user is the result of a select from our database. I need to create a hash with this...

heroku pgbackups:url command is no longer working?


ruby-on-rails,postgresql,ruby-on-rails-4,amazon-web-services,heroku
How do I download my dump directly from Amazon AWS S3 if heroku pgbackups:url b004 isn't working? Specifically, when I run this command it returns: ! Please add the pgbackups addon first via: ! heroku addons:add pgbackups And then when I run this command I get: ! No such add-on...

Rails shared controller actions


ruby-on-rails,ruby,ruby-on-rails-4
I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

Devise emails are not being sent using sendgrid while other emails are being sent well


ruby-on-rails-4,heroku,devise,sendgrid
I am using sendgrid to send emails in production my all other emails are being sent as expected but all the devise emails are not being sent neither a crash occur my in my production.rb I have config.action_mailer.raise_delivery_errors = false config.action_mailer.default_url_options = { :host => 'myapp.herokuapp.com' } config.action_mailer.delivery_method = :smtp...

ApplicationController helper method undefined in Rails


ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4
I'm trying to write a simple helper method that checks if a user's email address contains a specific domain name. The method is needed in all my controllers and depends on the state of current_user, so I felt the best place to put it would be in my ApplicationController. Depending...

Sortable in Rails 4


ruby-on-rails,jquery-ui,ruby-on-rails-4
I'm following Railcasts #147 using Rails 4 instead of 3. The method below is not passing in Rails 4. So far all, all is working except for updating the databse with the new sorted position. Any idea how I can mass update the records? def sort params[:faq].each_with_index do |id, index|...

implement has_many through association in rails 4


ruby-on-rails-4,activerecord,has-many-through
I am working with has_many :through association in Application. I implement association between models like :- in employee.rb class Employee < ActiveRecord::Base has_many :inventories, through: :employee_inventories end in inventory.rb class Inventory < ActiveRecord::Base has_many :employees, through: :employee_inventories end in employee_inventories.rb class EmployeeInventory < ActiveRecord::Base belongs_to :employee belongs_to :inventory end I...

Seeding fails validation for nested tables (validates_presence_of)


ruby-on-rails,ruby,validation,ruby-on-rails-4,associations
An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

How to send nested data in response , rails4?


ruby-on-rails,ruby-on-rails-4
I am using rails 4. I have a two models- "Company" & "Employees". Company has_many employees. I want to fetch the company and get all the employees in its nested dictionary in API like this, {"Company":{"name":"companyName", "total_employees":1000000, "Employees":[{"name":"xyz"}, {"name":"abc"}]} In company controller I tried respond_with(Company.for(@current_user.id)) In company model scope :for,...

How to limit access in Amazon S3 files to specific people?


ruby-on-rails-4,amazon-s3
I work on a SaaS application where Creators can create Groups and invite others to their Group to share files, chat and so on. Only people within specific group should have access to this group's files. People from other group must not have access to not their group's files. And...

Rails routing link to specific show


ruby-on-rails-4,routing
This question seems a little basic, but considering I have 'pages#show' with a show page with url 'history'. How could I add this specific show page to a link: = link_to 'History', pages_path(@?????) PD1: I would prefer avoid using :id since I tend to seed a lot of data, and...

Migrate from existing password_digest column?


ruby-on-rails,ruby-on-rails-4,devise,bcrypt
I have a custom User model with lots of rows. I have a password_digest column that I want to keep. (it comes from has_secure_password) And I also want to use Devise database authenticatable, but from my limited knowledge on Devise, I have to use the encrypted_password column. Is there a...

Javascript Changing Random Background Image Issue


javascript,html,ruby-on-rails,ruby-on-rails-4,background-image
I am on Rails 4, and finally got this javascript working. It changes randomly changes the background image every 10 seconds with a fadein fadeout effect. The only issue is every so often, an image will only load halfway... then it will start to flash and and get crazy. It...

rendering the partials in controller after the validation check


ruby-on-rails,ruby-on-rails-4,model-view-controller
I have two partial views for two different sign up forms. On my home page , based on the link one clicks on, I'm rendering respective form.(views/application/index) = link_to 'Mentor', new_user_path(user_role: true), :class =>'btn' = link_to 'Mentee', new_user_path, :class =>'btn' In views/users/new.html.haml , I'm checking the user role and redirecting...

Using the Rails console to delete odd-numbered records


ruby-on-rails-4,command-line,console
I'd like to delete records with odd numbered ID's from Hero table using the Rails console. Would someone be so kind as to suggest a way for me to do this? Kind Regards, Ryan...

Make instance variable accessible through hash in Ruby


ruby-on-rails,ruby,ruby-on-rails-4,activerecord
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Showing and editing has_many objects in Rails


ruby-on-rails,ruby-on-rails-4
I'm trying to do something that I imagine to be very basic, but I'm very new to Rails and am not sure what sure what I'm doing wrong. I've gone through several tutorials and searched for an answer and can't find what the issue is. Would appreciate any help! I've...

On rendering from controller, current_page method does not seem to work


ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller
I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Mongoid HABTM relationships across embedded documents


ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents
I'm trying to create a Mongoid N-N reference association between two embedded documents in Rails 4 however I'm finding it difficult to get my head round how this is done. I started by adding the HABTM association to the relevant models below (Track and Option) but of course I'm getting...

Trouble in RSpec test - saving parent record twice


ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes
I'm new at Rails programming, and my RSpec test is failing when trying to save nested records. The logs from the test suggest that ActiveRecord is trying to save the parent twice, which results in a silent database save failure. sign_up_spec.rb (sorry for the omission!) require 'rails_helper' RSpec.feature "Accounts", type:...

rails has_many at least one children has the value


sql,ruby-on-rails,ruby,ruby-on-rails-4,activerecord
Let say I have a Group of Users and User has a enum, which described it's mood. class Group < AR::Base has_many :users class User < AR::Base belongs_to :group enum mood: %i(good bad ugly) How can I find all groups, where at least one User has the good mood? Which...

How to use Rails #update_attribute with array field?


ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord
Each question has an array of tags. schema.rb: create_table "questions", force: true do |t| t.text "tags", default: [], array: true How to atomically append to tags? How to prevent dups within the array? I tried question.update_attribute tags: tags << :ruby, but this doesn't work. Rails 4.17 and Postgres. EDIT: This...

Stack level too deep because recursion


ruby-on-rails,ruby,ruby-on-rails-4,twitter
I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

Invalid form submission clears session in Rails 4


ruby-on-rails-4,session-cookies,form-submit,session-state
I'm using a session to auto fill the first half of a form in Rails 4. The first time a customer submits a form (featuring their details and product details), the customers details are stored into a session. Upon subsequent forms (additional orders), the customer's details are pulled from the...

How to exclude guest users from getting emailed Rails 4 Devise


ruby-on-rails,email,ruby-on-rails-4,devise,mailer
Just set up my first mailer on Rails 4. I have a welcome email sent to new users as soon as they sign up (create) for a new account using devise. I also have devise set up so that if a current_user is not found, a guest user will be...

Ruby if else statement one line not working


ruby-on-rails,ruby,ruby-on-rails-4
I have the following properly working line in a view that adds a class depending on the current_page of the user: <li class="hvr-bottom <%= 'active' if current_page?(root_path) %>"> <%= link_to "Home", root_path %> </li> Now I would also like to add a different class for the else situation, and I...

Facing issue in edit-update action in nested form in rails4?


ruby-on-rails,ruby-on-rails-4,nested-forms
Hi I am using gem "nested_form" and included has_many association in my app sample code is : class Question < ActiveRecord::Base has_many :choices accepts_nested_attributes_for :choices end and in my controller have included this : class QuestionsController < ApplicationController before_action :set_questions, only: [:edit, :update] def edit end def update if @question.update_attributes(question_params)...

Why isn't the format date of the Rails view being properly displayed with the initializer?


ruby-on-rails,ruby,ruby-on-rails-4,erb,view-helpers
On my view view, I have the following format I want to output: <tr> <th>Released:</th> <td> <%= movie.release_at.to_s(:release_date) %> (<%= time_ago_in_words(movie.release_at) %>) </td> </tr> The exact format I want is "Month Day, Year", so I created an initialize file with the following: Date::DATE_FORMATS[:default] = "%B %e, %Y" My database schema...

How to iterate data from database to become a radio button in template?


ruby-on-rails,ruby,ruby-on-rails-4
I am using Rails 4.2 and Ruby 2.1.5 Here is my radio button code of my new template: <%= form_for @api, :url => commons_path do |f| %> <div class="form-group"> <%= f.label :status, "Status", class: "col-sm-2 control-label" %> <div class="col-sm-8"> <%= f.radio_button :status, 'success' %> <%= label_tag(:status, "Success") %> <%= f.radio_button...