How preview multiple images with nested form rails - ruby-on-rails

I'm using paperclip to upload images and nested form.
I want to preview images as input, not just an image.
This is my form.
= nested_form_for #anime, html:{multipart:true} do |f|
- if #anime.errors.any?
#error_explanation
%h2= "#{pluralize(#anime.errors.count, "error")} prohibited this anime from being saved:"
%ul
- #anime.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :name
= f.text_area :name
.fields
=f.fields_for :images do |i|
=i.file_field :content
=i.link_to_remove "Remove"
.field
=f.link_to_add "add Image", :images
.actions
= f.submit 'Save'
This is my model.
class Image < ApplicationRecord
belongs_to :imageable, :polymorphic => true, optional:true
has_attached_file :content, :styles=>{:medium => "300x300>", :thumb => "100x100>"}
validates_attachment_content_type :content, :content_type => %w(image/jpeg image/jpg image/png)
end
class Anime < ApplicationRecord
has_many :images, :as => :imageable, dependent: :destroy
accepts_nested_attributes_for :images, :allow_destroy => true
end
This is my controller
class AnimesController < ApplicationController
before_action :set_anime, only: [:show, :edit, :update, :destroy]
# GET /animes
# GET /animes.json
def index
#animes = Anime.all
end
# GET /animes/1
# GET /animes/1.json
def show
end
# GET /animes/new
def new
#anime = Anime.new
#anime.images.build
end
# GET /animes/1/edit
def edit
end
# POST /animes
# POST /animes.json
def create
#anime = Anime.new(anime_params)
respond_to do |format|
if #anime.save
format.html { redirect_to #anime, notice: 'Anime was successfully created.' }
format.json { render :show, status: :created, location: #anime }
else
format.html { render :new }
format.json { render json: #anime.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /animes/1
# PATCH/PUT /animes/1.json
def update
respond_to do |format|
if #anime.update(anime_params)
format.html { redirect_to #anime, notice: 'Anime was successfully updated.' }
format.json { render :show, status: :ok, location: #anime }
else
format.html { render :edit }
format.json { render json: #anime.errors, status: :unprocessable_entity }
end
end
end
# DELETE /animes/1
# DELETE /animes/1.json
def destroy
#anime.destroy
respond_to do |format|
format.html { redirect_to animes_url, notice: 'Anime was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_anime
#anime = Anime.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def anime_params
params.require(:anime).permit(:name, images_attributes: [:content])
end
end
Please help me
Thanks so much.
ignore this message

Related

rails strong parameters not work correctly

i have a rails app. i have strange problem in saving form
this is my ticket model .
class Ticket < ApplicationRecord
belongs_to :user
has_many :ticketissues , inverse_of: :ticket
accepts_nested_attributes_for :ticketissues, :reject_if => lambda { |a| a[:body].blank? }
end
this is ticketisue model
class Ticketissue < ApplicationRecord
belongs_to :user
belongs_to :ticket
validates :body, presence: true
end
this is ticket controller
class TicketsController < ApplicationController
before_action :set_ticket, only: [:show, :edit, :update, :destroy]
# GET /tickets
# GET /tickets.json
def index
#tickets = Ticket.all
end
# GET /tickets/1
# GET /tickets/1.json
def show
end
# GET /tickets/new
def new
#ticket = Ticket.new
end
# GET /tickets/1/edit
def edit
end
# POST /tickets
# POST /tickets.json
def create
#ticket = Ticket.new(ticket_params)
#ticket.user_id = current_user.id
#ticket.ticketissues.build
respond_to do |format|
if #ticket.save
format.html { redirect_to #ticket, notice: 'Ticket was successfully created.' }
format.json { render :show, status: :created, location: #ticket }
else
format.html { render :new }
format.json { render json: #ticket.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tickets/1
# PATCH/PUT /tickets/1.json
def update
respond_to do |format|
if #ticket.update(ticket_params)
format.html { redirect_to #ticket, notice: 'Ticket was successfully updated.' }
format.json { render :show, status: :ok, location: #ticket }
else
format.html { render :edit }
format.json { render json: #ticket.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tickets/1
# DELETE /tickets/1.json
def destroy
#ticket.destroy
respond_to do |format|
format.html { redirect_to tickets_url, notice: 'Ticket was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ticket
#ticket = Ticket.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def ticket_params
params.require(:ticket).permit(:subject, :subsubject, :user_id, ticketissues_attributes: [
:body, :id, :_destroy] )
#params.require(:ticket).permit!
end
end
and my view is like this
<%= f.input :subject , collection: [ "تغییر اطلاعات کسب و کار",
"تغییر اطلاعات یک کوپن",
"سایر موارد"] %>
<%= f.input :subsubject %>
<!-- <%= f.association :user %> -->
</div>
<%= f.simple_fields_for :ticketissue do |p| %>
<%= p.input :body %>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
but when i want to create a ticket , form will not save to database
and i get this error:
Started POST "/tickets" for 127.0.0.1 at 2017-04-11 23:52:33 +0430
Processing by TicketsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"fsl6nTe0PjmBKpeuh16BRFlYOw0MB93LEYDVEAl6TtT/uu/LwGTA0P2q0bRxIxBUqHqZINXHntrZLt7MuCG84Q==", "ticket"=>{"subject"=>"تغییر اطلاعات کسب و کار", "subsubject"=>"lk", "ticketissue"=>{"body"=>"lkjkjkjkjkkjkj"}}, "commit"=>"Create Ticket"}
Unpermitted parameter: ticketissue
but when i use console and this command:
Ticket.create(subject: 'test' , subsubject: 'ticket test' , ticketissues_attributes: [{body: "[some thing" }] )
every things work fines and all data save.
tanks for read and help.
You must use the plural here
= f.simple_fields_for :ticketissues do |p|

Rails 4: Duplicated file_field input on Nested Form

I have a model "post" and a model "photo". The model post have a nested form from photo to upload images with association. The upload works fine, but everytime I go to edit the post, I have a new input to each image uploaded and one more input to upload a new image. I want to have just the input to upload a new file and hide or not load the others.
Here is my code:
<%= f.fields_for :photos do |photo| %>
<%= photo.file_field :image, class: "form-control" %>
<% end %>
Controller:
module Admin
class SeminovosController < SuperAdminController
before_action :set_seminovo, only: [:show, :edit, :update, :destroy]
# GET /seminovos
# GET /seminovos.json
def index
#seminovos = Seminovo.all
#seminovo = Seminovo.new
#seminovo.photos.build
#expires_in 3.hours, :public => true, 'max-stale' => 0
end
# GET /seminovos/1
# GET /seminovos/1.json
def show
end
# GET /seminovos/new
def new
#seminovo = Seminovo.new
#seminovo.photos.build
#seminovo.photos
end
# GET /seminovos/1/edit
def edit
#seminovo.photos.build
#seminovo.photos
end
# POST /seminovos
# POST /seminovos.json
def create
##seminovo = Seminovo.new(seminovo_params)
respond_to do |format|
#seminovo = Seminovo.new(seminovo_params)
#seminovo.save
format.html { redirect_to #seminovo }
format.js
# if #seminovo.save
# format.html { redirect_to #seminovo, notice: 'Seminovo was successfully created.' }
# format.json { render :show, status: :created, location: #seminovo }
# else
# format.html { render :new }
# format.json { render json: #seminovo.errors, status: :unprocessable_entity }
# end
end
end
# PATCH/PUT /seminovos/1
# PATCH/PUT /seminovos/1.json
def update
respond_to do |format|
if #seminovo.update(seminovo_params)
format.html { redirect_to #seminovo, notice: 'Seminovo was successfully updated.' }
format.json { render :show, status: :ok, location: #seminovo }
else
format.html { render :edit }
format.json { render json: #seminovo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /seminovos/1
# DELETE /seminovos/1.json
def destroy
#seminovo.destroy
respond_to do |format|
format.html { redirect_to seminovos_url, notice: 'Seminovo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_seminovo
#seminovo = Seminovo.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def seminovo_params
params.require(:seminovo).permit(:name, :price, :marca_id, :tipo_id, :ano_modelo,
:portas, :km_rodados, :combustivel, :placa, :cor, :desc,
:video, :destaque, :photo_id, :slug,
photos_attributes: [ :id, :image, :image_uid, :image_name, :desc,
:seminovos_id, :_destroy ])
end
end
end
Remove
#seminovo.photos.build
#seminovo.photos
from new and edit action.
Then replace
<%= f.fields_for :photos do |photo| %>
<%= photo.file_field :image, class: "form-control" %>
<% end %>
With
<%= f.fields_for :photos, #seminovo.photos.new do |photo| %>
<%= photo.file_field :image, class: "form-control" %>
<% end %>

Rails, How i can create grouped_select?

I'm new in rails and i need a help.
I wanna to do a grouped selection on rails but i dont know how i can do it.
i have 3 db tables cars, car_brands and car_models. When i add new car i need to select car model, how i can do it with gtouped selection.
models/car_brand.rb
class CarBrand < ActiveRecord::Base
has_many :cars
has_many :car_models
mount_uploader :logo, CarBrandImgUploader
end
models/car_model.rb
class CarModel < ActiveRecord::Base
has_many :cars
belongs_to :car_brand
end
cars_controller.rb
class CarsController < ApplicationController
before_action :set_car, only: [:show, :edit, :update, :destroy]
before_action :set_model, only: [:index, :new, :edit]
# GET /cars
# GET /cars.json
def index
#cars = Car.all
end
# GET /cars/1
# GET /cars/1.json
def show
end
# GET /cars/new
def new
#car = Car.new
end
# GET /cars/1/edit
def edit
end
# POST /cars
# POST /cars.json
def create
#car = Car.new(car_params)
respond_to do |format|
if #car.save
if params[:ImagesCars]
params[:ImagesCars]['image'].each do |a|
#ImagesCar = #car.ImagesCars.create!(:image => a, :car_id => #car.id)
end
end
format.html { redirect_to #car, notice: 'Car was successfully created.' }
format.json { render :show, status: :created, location: #car }
else
format.html { render :new }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cars/1
# PATCH/PUT /cars/1.json
def update
respond_to do |format|
if #car.update(car_params)
if params[:ImagesCars]
params[:ImagesCars]['image'].each do |a|
#ImagesCar = #car.ImagesCars.create!(:image => a, :car_id => #car.id)
end
end
format.html { redirect_to #car, notice: 'Car was successfully updated.' }
format.json { render :show, status: :ok, location: #car }
else
format.html { render :edit }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cars/1
# DELETE /cars/1.json
def destroy
#car.destroy
respond_to do |format|
format.html { redirect_to cars_url, notice: 'Car was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_car
#car = Car.find(params[:id])
end
def set_model
#models = CarModel.all
#brands = CarBrand.all
end
# Never trust parameters from the scary internet, only allow the white list through.
def car_params
params.require(:car).permit(:title_en, :keys_en, :description_en, :text_en, :title_fr, :keys_fr, :description_fr, :text_fr, :title_ru, :keys_ru, :description_ru, :text_ru, :title_es, :keys_es, :description_es, :text_es, :model_id, :brand_id, :price_day, :price_week, :p_info, :images_cars => [:id, :car_id, :image])
end
end
cars/new.html.haml
= simple_form_for(#car, html: { role: 'form', multipart: true }) do |f|
= f.input :price_day, as: :integer, input_html: {class: 'form-control', placeholder: 'Price Day ej: 150'}
= f.cktext_area :text_en, as: :text, input_html: { class: 'form-control' }, :label => 'EN Website Content Text EN'
=f.input :model_id, collection: #models, as: :grouped_select, group_method: :brand_id
= f.submit 'Save'
i get this error:
undefined method `map' for nil:NilClass
Please help or explain how i can do the grouped selection.
Thx

accepts_nested_attributes_for not working properly

I'm fairly new to rails, building my first app. I'm running rails 4 w/ bootstrap 3. I'm trying to get a complex form to work. I have two models:
class Employee < ActiveRecord::Base
belongs_to :company
belongs_to :user, :through => :company
has_one :position
accepts_nested_attributes_for :position
end
class Position < ActiveRecord::Base
belongs_to :employees
accepts_nested_attributes_for :employees
end
I have a form where the User can create a new job title (Position Model) and select the employees (Employees Model) that position will be applied to. Basically it's a single form that will add fields to 2 different database tables (Position and Employee).
This is my view:
<%= simple_form_for(#position) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :job_title %>
<%= f.input :job_description %>
</div>
<%= f.fields_for :Employee do |f| %>
<%= f.input :employee_title, label: "Apply to:", collection: Employee.all, label_method: :first_name, as: :check_boxes %>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Below are the controllers:
class PositionsController < ApplicationController
before_action :set_position, only: [:show, :edit, :update, :destroy]
# GET /positions
# GET /positions.json
def index
#positions = Position.all
end
# GET /positions/1
# GET /positions/1.json
def show
end
# GET /positions/new
def new
#position = Position.new
end
# GET /positions/1/edit
def edit
end
# POST /positions
# POST /positions.json
def create
#position = Position.new(position_params)
respond_to do |format|
if #position.save
format.html { redirect_to #position, notice: 'position was successfully created.' }
format.json { render action: 'show', status: :created, location: #position }
else
format.html { render action: 'new' }
format.json { render json: #position.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /positions/1
# PATCH/PUT /positions/1.json
def update
respond_to do |format|
if #position.update(position_params)
format.html { redirect_to #position, notice: 'position was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #position.errors, status: :unprocessable_entity }
end
end
end
# DELETE /positions/1
# DELETE /positions/1.json
def destroy
#position.destroy
respond_to do |format|
format.html { redirect_to positions_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_position
#position = Position.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def position_params
params.require(:position).permit(:position_title, :position_description, :position_create_date)
end
end
class EmployeesController < ApplicationController
# encoding: UTF-8
before_action :set_employee, only: [:show, :edit, :update, :destroy]
# GET /employees
# GET /employees.json
def index
#employees = Employee.all
end
# GET /employees/1
# GET /employees/1.json
def show
end
# GET /employees/new
def new
#employee = Employee.new
end
# GET /employees/1/edit
def edit
end
# POST /employees
# POST /employees.json
def create
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to #employee, notice: 'Employee was successfully created.' }
format.json { render action: 'show', status: :created, location: #employee }
else
format.html { render action: 'new' }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1
# PATCH/PUT /employees/1.json
def update
respond_to do |format|
if #employee.update(employee_params)
format.html { redirect_to #employee, notice: 'Employee was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
#employee.destroy
respond_to do |format|
format.html { redirect_to employees_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:first_name, :last_name, :employee_title)
end
end
The problem I'm facing is I get the form to render perfectly, but when I submit it, only fields that belong to the Position model get recorded. The :employee_title stays blank. Any suggestions what the problem is?
Thank you!!
Too many points to fit in a comment:
belongs_to :employees should be singular: belongs_to :employee
Your fields_for should be like (differentiate the ff from parent form):
<%= f.fields_for :Employee do |ff| %>
<%= ff.input :employee_title, label: "Apply to:", collection: Employee.all,
label_method: :first_name, as: :check_boxes %>
<% end %>
If it doesn't work, supply your controller also and I'll update my answer.
Edit:
After seeing your controllers, it seems most likely to be case of unpermitted params.
In position_controller.rb add employee params to position params
def position_params
params.require(:position).permit(:position_title, :position_description, :position_create_date, employees_attributes: [:first_name, :last_name, :employee_title])
end

Ruby on Rails: many-to-many association undefined methode on creation

I have set up members and teams models using has_many through association.
member.rb
has_many :teams, :through => :team_members
has_many :team_members
team.rb
has_many :members, :through => :team_members
has_many :team_members
team_member.rb
belongs_to :member
belongs_to :team
When I try to create a new team, I get this error:
undefined method `name' for nil:NilClass
params are:
{"utf8"=>"✓",
"authenticity_token"=>"aXpMxWxGlhogfn9EbBWciSjoMrYXbPxG8Kzha14na58=",
"team"=>{"name"=>"Ruby",
"email"=>"email#email.com",
"language"=>"En",
"link"=>"",
"logo"=>#<ActionDispatch::Http::UploadedFile:0xb3907f0 #original_filename="You-Are-Great-.gif",
#content_type="image/gif",
#headers="Content-Disposition: form-data; name=\"team[logo]\"; filename=\"You-Are-Great-.gif\"\r\nContent-Type: image/gif\r\n",
#tempfile=#<File:/tmp/RackMultipart20120723-1907-m3bi79>>},
"commit"=>"Create Team"}
The create method in teams_controller.rb is:
#team = Team.new(params[:team])
The team doesn't get created unless I assign the attributes manually one by one like
#team = Team.new(:name => params[:team][:name], :email => params[:team][:email]...)
and so! any ideas why?
EDIT:
teams_controller.rb:
class TeamsController < ApplicationController
# GET /teams
# GET /teams.json
def index
#teams = Team.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #teams }
end
end
# GET /teams/1
# GET /teams/1.json
def show
#team = Team.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #team }
end
end
# GET /teams/new
# GET /teams/new.json
def new
#team = Team.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #team }
end
end
# GET /teams/1/edit
def edit
#team = Team.find(params[:id])
end
# POST /teams
# POST /teams.json
def create
raise params.to_yaml
#team = Team.new(params[:team])
respond_to do |format|
if #team.save
#team_member = TeamMember.new(:team_id => #team.id, :member_id => current_member.id,
:accepted => true, :leader => true, :joined => Time.now)
if #team_member.save
format.html { redirect_to team_path(#team), notice: 'Team was successfully created.' }
format.json { render json: #team, status: :created, location: #team }
else
#team.destroy
format.html { render action: "new" }
format.json { render json: #team.errors, status: :unprocessable_entity }
end
else
format.html { render action: "new" }
format.json { render json: #team.errors, status: :unprocessable_entity }
end
end
end
# PUT /teams/1
# PUT /teams/1.json
def update
#team = Team.find(params[:id])
respond_to do |format|
if #team.update_attributes(params[:team])
format.html { redirect_to #team, notice: 'Team was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #team.errors, status: :unprocessable_entity }
end
end
end
# DELETE /teams/1
# DELETE /teams/1.json
def destroy
#team = Team.find(params[:id])
#team.destroy
respond_to do |format|
format.html { redirect_to teams_url }
format.json { head :no_content }
end
end
end
team.rb model:
class Team < ActiveRecord::Base
attr_accessible :name, :email, :language, :link, :logo, :team_leader
validates_presence_of :name
validates_presence_of :email
validates_presence_of :language
validates_uniqueness_of :name
has_many :leaders, :class_name => "TeamMember", :conditions => { :leader => true }
has_many :members, :through => :team_members
has_many :team_members, :conditions => { :accepted => true, :active => true }
has_attached_file :logo,
:styles => { :medium => "320x180>", :thumb => "100x100>" },
:url => "/assets/teams/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/teams/:id/:style/:basename.:extension"
end

Resources