I'm trying to save updates made in the inline tinymce editor in my rails app, but I don't know how to do it exactly as I want. I want the inline editor to be able to save while the view is 'html_safe'. I can save it fine if the form area is a text area (i.e. <div class="editor"><%= form.text_area :content %></div>), but I want to have the view in inline editor format so you can see your changes on the fly.
In the logs, it looks like the invitation params are closing before it's including the changes needed. How do I do this so that the inline editor changes are saved correctly?
Note: Everything else is working correctly, except the changes to the <%= #invitation.content %> are not being saved.
View:
<%= form_with(model: #invitation, local: true) do |form| %>
<%= form.hidden_field :event_id, value: #event.id %>
<div class="editor"><%= #invitation.content.html_safe %></div>
<script type="text/javascript">
tinyMCE.init({
selector: '.editor',
menubar: false,
inline: true,
plugins: "save",
toolbar: "save"
});
</script>
<% end %>
And my output from the log is:
Processing by InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2ssewH/CSN7is0P2LVrMkEmwZXcgmQqjWTjgrE6gGqAEv4dmLXFjEuOFJ9TRia+JF59SB6kKu5Le1xvt/FoxPg==", "invitation"=>{"event_id"=>"29"}, "mce_0"=>"<h1>Second Test Event CHANGEHERE!</h1>\r\n<h2>09/02/18 # 04:20</h2>\r\n<p> </p>\r\n<hr />\r\n<p>Bring Cheese</p>", "commit"=>"Update Invitation", "id"=>"7"}
Invitation Load (2.6ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT $2 [["id", 7], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:66
(0.3ms) BEGIN
↳ app/controllers/invitations_controller.rb:43
Event Load (1.8ms) SELECT "events".* FROM "events" WHERE "events"."id" = $1 LIMIT $2 [["id", 29], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:43
(0.3ms) COMMIT
↳ app/controllers/invitations_controller.rb:43
Redirected to http://localhost:3000/events/29
And my controller is a basic object controller:
class InvitationsController < ApplicationController
before_action :set_invitation, only: [:show, :edit, :update, :destroy]
# GET /invitations
# GET /invitations.json
def index
#invitations = Invitation.all
end
# GET /invitations/1
# GET /invitations/1.json
def show
end
# GET /invitations/new
def new
#invitation = Invitation.new
end
# GET /invitations/1/edit
def edit
end
# POST /invitations
# POST /invitations.json
def create
#invitation = Invitation.new(invitation_params)
respond_to do |format|
if #invitation.save
format.html { redirect_to #invitation, notice: 'Invitation was successfully created.' }
format.json { render :show, status: :created, location: #invitation }
else
format.html { render :new }
format.json { render json: #invitation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /invitations/1
# PATCH/PUT /invitations/1.json
def update
respond_to do |format|
if #invitation.update(invitation_params)
format.html { redirect_to #invitation.event, notice: 'Invitation was successfully updated.' }
format.json { render :show, status: :ok, location: #invitation }
else
format.html { render :edit }
format.json { render json: #invitation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /invitations/1
# DELETE /invitations/1.json
def destroy
#invitation.destroy
respond_to do |format|
format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_invitation
#invitation = Invitation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def invitation_params
params.require(:invitation).permit(:name, :content, :event_id)
end
end
Related
Hi I am playing around in rails and have built a little listing application.
My application has a listing model that has many tags through a has and belongs to many join table.
the join table is called listings_tags
The problem I have is that I cannot save the listing_tag association during create or update.
I can see in console
Started PATCH "/listings/92" for 127.0.0.1 at 2018-08-15 12:45:58 +1000
Processing by ListingsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5isdLs2FiToZxtm1ZVPP0y0lKtnfyoLA8Njv4GBwWVH1M3TIm2IUW9ts5RR06OpQz8tgSBitZ7Rm69uVIifevQ==", "listing"=>{"name"=>"Canteen Coffee", "streetAddres"=>"19 Park Avenue", "suburb_id"=>"31", "post_code_id"=>"2", "region_id"=>"1", "country_id"=>"2", "telephone"=>"+61416650204", "url"=>"http://canteencoffee.com.au/canteen-kitchen/", "tag_ids"=>["", "1"]}, "commit"=>"Update Listing", "id"=>"92"}
Listing Load (0.2ms) SELECT "listings".* FROM "listings" WHERE "listings"."id" = $1 LIMIT $2 [["id", 92], ["LIMIT", 1]]
Unpermitted parameter: :tag_ids
(1.8ms) BEGIN
Suburb Load (5.4ms) SELECT "suburbs".* FROM "suburbs" WHERE "suburbs"."id" = $1 LIMIT $2 [["id", 31], ["LIMIT", 1]]
(1.7ms) COMMIT
Redirected to http://localhost:3000/listings/92
Completed 302 Found in 21ms (ActiveRecord: 9.0ms)
Obviously my issue is the :tag_ids
so I tried changing my listing params.require(:listing).permit() to include listing_attributes: [:id], tags: [:id] and :tag_ids
its killing me :) please help
Listing Model
class Listing < ApplicationRecord
has_and_belongs_to_many :tags
belongs_to :suburb
has_one :post_code, through: :suburb
accepts_nested_attributes_for :tags
def self.search(term)
if term
where('name LIKE ?', "%#{term}%")
else
order('id DESC')
end
end
end
Tag Model
class Tag < ApplicationRecord
has_and_belongs_to_many :listings
end
Listings Tags Schema
create_table "listings_tags", id: false, force: :cascade do |t|
t.bigint "listing_id", null: false
t.bigint "tag_id", null: false
t.index ["listing_id", "tag_id"], name: "index_listings_tags_on_listing_id_and_tag_id"
end
Listings Controller
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
# GET /listings
# GET /listings.json
def index
#listings = Listing.search(params[:term])
end
# GET /listings/1
# GET /listings/1.json
def show
#listing = Listing.find(params[:id])
#tags = #listing.tags
#suburb = #listing.suburb
#postcode = #suburb.post_code
end
# GET /listings/new
def new
#listing = Listing.new
end
# GET /listings/1/edit
def edit
end
# POST /listings
# POST /listings.json
def create
#listing = Listing.new(listing_params)
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render :show, status: :created, location: #listing }
else
format.html { render :new }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /listings/1
# PATCH/PUT /listings/1.json
def update
respond_to do |format|
if #listing.update(listing_params)
format.html { redirect_to #listing, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: #listing }
else
format.html { render :edit }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /listings/1
# DELETE /listings/1.json
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:name, :streetAddress, :telephone, :url, :term, :suburb_id, :post_code_id, :region_id, :country_id, :tag_ids)
end
end
Tags Controller
class TagsController < ApplicationController
before_action :set_tag, only: [:show, :edit, :update, :destroy]
# GET /tags
# GET /tags.json
def index
#tags = Tag.all
end
# GET /tags/1
# GET /tags/1.json
def show
#tag = Tag.find(params[:id])
#listings = #tag.listings
end
# GET /tags/new
def new
#tag = Tag.new
end
# GET /tags/1/edit
def edit
end
# POST /tags
# POST /tags.json
def create
#tag = Tag.new(tag_params)
respond_to do |format|
if #tag.save
format.html { redirect_to #tag, notice: 'Tag was successfully created.' }
format.json { render :show, status: :created, location: #tag }
else
format.html { render :new }
format.json { render json: #tag.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tags/1
# PATCH/PUT /tags/1.json
def update
respond_to do |format|
if #tag.update(tag_params)
format.html { redirect_to #tag, notice: 'Tag was successfully updated.' }
format.json { render :show, status: :ok, location: #tag }
else
format.html { render :edit }
format.json { render json: #tag.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tags/1
# DELETE /tags/1.json
def destroy
#tag.destroy
respond_to do |format|
format.html { redirect_to tags_url, notice: 'Tag was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tag
#tag = Tag.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params.require(:tag).permit(:name)
end
end
Form
<%= bootstrap_form_for(#listing, local: true) do |form| %>
<%= form.text_field :name, id: :listing_name %>
<%= form.text_field :streetAddress, id: :listing_streetAddress %>
<%= form.collection_select(:suburb_id, Suburb.all, :id, :name) %>
<%= form.collection_select(:post_code_id, PostCode.all, :id, :number) %>
<%= form.collection_select(:region_id, Region.all, :id, :name) %>
<%= form.collection_select(:country_id, Country.all, :id, :name) %>
<%= form.text_field :telephone, id: :listing_telephone %>
<%= form.text_field :url, id: :listing_url %>
<%= form.select :tag_ids, Tag.all.pluck(:name, :id), {}, { multiple: true, class: "selectize" } %>
<%= form.submit %>
<% end %>
I really appreciate your help. I am sure it is probably something simple that I am doing wrong.
try this
params.require(:listing).permit(:name, :streetAddress, :telephone, :url, :term, :suburb_id, :post_code_id, :region_id, :country_id, :tag_ids => [])
source : https://github.com/rails/strong_parameters
I am trying to create new object and to store it into the Database but I cannot understand why I am getting the following error: Here you can see the mistake:
Started POST "/cruises" for 127.0.0.1 at 2017-09-26 16:34:59 +0100
Processing by CruisesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OkFmCPhl0pjFezWCsxp+c16wr3j9nbsdLIdgj+PsCMgSDmTzBoEJQ69tB8IA3uNayLRO+LMTi/73YqYCMImtCA==", "cruise"=>{"name"=>"NewAsasa", "ship_id"=>""}, "commit"=>"Create Cruise"}
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendering cruises/new.html.erb within layouts/application
Rendered cruises/_form.html.erb (3.6ms)
Rendered cruises/new.html.erb within layouts/application (4.4ms)
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.1ms)
ActionView::Template::Error (undefined method `map' for nil:NilClass
Did you mean? tap):
18:
19: <div class="field">
20: <em><%= f.label :ship_id %></em>
21: <%= f.collection_radio_buttons( :ship_id, #ships, :id, :name ) %>
22: </div>
23:
24: <div class="actions">
CruiseController - ""here you can see more about the controller below:I just need to write more text because it gives me error when I try to put this code, so do not read this explaination here it is for""
class CruisesController < ApplicationController
before_action :set_cruise, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :redirect_if_not_found
# GET /cruises
# GET /cruises.json
def index
#cruises = Cruise.all
end
# GET /cruises/1
# GET /cruises/1.json
def show
end
# GET /cruises/new
def new
#cruise = Cruise.new
#ships = Ship.all
end
# GET /cruises/1/edit
def edit
#ships = Ship.all
end
# POST /cruises
# POST /cruises.json
def create
#cruise = Cruise.new(cruise_params)
respond_to do |format|
if #cruise.save
format.html { redirect_to #cruise, notice: 'Cruise was successfully created.' }
format.json { render :show, status: :created, location: #cruise }
else
format.html { render :new }
format.json { render json: #cruise.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cruises/1
# PATCH/PUT /cruises/1.json
def update
respond_to do |format|
if #cruise.update(cruise_params)
format.html { redirect_to #cruise, notice: 'Cruise was successfully updated.' }
format.json { render :show, status: :ok, location: #cruise }
else
format.html { render :edit }
format.json { render json: #cruise.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cruises/1
# DELETE /cruises/1.json
def destroy
#cruise.destroy
respond_to do |format|
format.html { redirect_to cruises_url, notice: 'Cruise was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cruise
#cruise = Cruise.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cruise_params
params.require(:cruise).permit(:name, :ship_id)
end
end
Whatever you are iterating over in your controller is nil. Based on the code you have shown I am assuming it is #ships. I bet if you put puts #ships in your controller it will log nil.
Your save fails in the create action, (rollback transaction) so the if condition of the create action trigger the render :new.
However, it is a render, not a redirect, that mean the new action is not executed, and both #cruise and #ship does not exist (undefined).
Finally during the rendering of the new view, an error is triggered because #ships is undefined.
EDIT : I made an error, #ships is not nil it just does not exist (undefined).
I have a server with devise and simple-authentication-token, and a client that use activeResource to authenticate user from server by json. The authantication works fine, but when I try retrieve an entity, the activeResource give me an internal server error. What do I need make to treat this error?
codeStarted GET "/news/1.jsonuser_email=mauricio1#gmail.com&user_token=JcmL-bouqbxSzeNznEb" for ::1 at 2015-05-08 16:41:13 -0300
Processing by NewsController#show as JSON
Parameters: {"user_email"=>"mauricio1#gmail.com", "user_token"=>"JcmL-bouqbxSzeNznEb", "id"=>"1"}
Completed 500 Internal Server Error in 114ms
ActiveResource::Redirection (Failed. Response code = 302. Response message = Found . => http://localhost:3001/users/sign_in.json):
app/controllers/news_controller.rb:68:in `set_news'
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (5.0ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (21.6ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/_markup.html.erb (0.3ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.5ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.4ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/console.js.erb within layouts/javascript (35.1ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.5ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.2/lib/web_console/templates/index.html.erb (144.0ms)
My NewsController.rb
class NewsController < ApplicationController
before_action :set_news, only: [:show, :edit, :update, :destroy]
# GET /news
# GET /news.json
def index
#news = News.all
end
# GET /news/1
# GET /news/1.json
def show
end
# GET /news/new
def new
#news = News.new
end
# GET /news/1/edit
def edit
end
# POST /news
# POST /news.json
def create
#news = News.new(news_params)
respond_to do |format|
if #news.save
format.html { redirect_to #news, notice: 'News was successfully created.' }
format.json { render :show, status: :created, location: #news }
else
format.html { render :new }
format.json { render json: #news.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /news/1
# PATCH/PUT /news/1.json
def update
respond_to do |format|
if #news.update(news_params)
format.html { redirect_to #news, notice: 'News was successfully updated.' }
format.json { render :show, status: :ok, location: #news }
else
format.html { render :edit }
format.json { render json: #news.errors, status: :unprocessable_entity }
end
end
end
# DELETE /news/1
# DELETE /news/1.json
def destroy
#news.destroy
respond_to do |format|
format.html { redirect_to news_index_url, notice: 'News was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_news
#news = News.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def news_params
params[:news]
end
end
Problem resolved with:
def set_news
begin
#news = News.find(params[:id])
rescue ActiveResource::Redirection
respond_to do |format|
format.json { render :json => { :state => {:code => 403, :message => "Forbidden"} }, :status => :forbidden }
end
rescue ActiveResource::ResourceNotFound
respond_to do |format|
format.json { render :json => { :state => {:code => 404, :message => "Not Found"} }, :status => :not_found }
end
rescue Exception => e
respond_to do |format|
format.json { render :json => { :state => {:code => 422, :message => "Unprocessabel Entity"} }, :status => :unprocessable_entity }
end
end
end
I'm using this example to create multiple image uploads using Carrierwave Rails 4 multiple image or file upload using carrierwave. For some reason if I edit the Post and try to upload a different image it doesn't update.
listings_controller.rb
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => [:show, :index]
def index
#listings = Listing.order('created_at DESC')
respond_to do |format|
format.html
format.json { render json: #listings }
end
end
def show
#image_attachments = #listing.image_attachments.all
end
def new
#listing = Listing.new
#listing.user = current_user
#image_attachment = #listing.image_attachments.build
end
def edit
end
def create
#listing = Listing.new(listing_params)
#listing.created_at = Time.now
#listing.user = current_user
respond_to do |format|
if #listing.save
params[:image_attachments]['image'].each do |a|
#image_attachment = #listing.image_attachments.create!(:image => a, :listing_id => #listing.id)
end
format.html { redirect_to #listing, notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #listing.update(listing_params)
flash[:notice] = 'Deal was successfully updated.'
format.html { redirect_to #listing }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:condition, :listing_title, :nickname, :listing_size, :listing_price, :user_id, image_attachments_attributes: [:id, :listing_id, :image])
end
end
listing form
<%= form_for(#listing, :html => { :class => 'form', :multipart => true }) do |f| %>
<% if #listing.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#listing.errors.count, "error") %> prohibited this listing from being saved:</h2>
<ul>
<% #listing.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.fields_for :image_attachments do |p| %>
<div>
<%= p.label :image %>
<%= p.file_field :image, :multiple => true, name: "image_attachments[image][]", :class => 'upload' %>
</div>
<% end %>
<div class="actions">
<%= f.submit 'Submit', :class => 'submitButton' %>
</div>
<% end %>
listing.rb
has_many :image_attachments
accepts_nested_attributes_for :image_attachments
Any help? Thanks.
UPDATE
This is the log ouput when I try to update the image field. "about.png" is the new image I'm trying to upload.
Started PATCH "/listings/nike-air-max-90" for 127.0.0.1 at 2014-07-16 11:40:14 -0400
Processing by ListingsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LU1ADy5JqfuX9CMDtcG/dmGgu9nuvplDQrVixfICsS4=", "listing"=>{"listing_title"=>"Nike Air Max 90", "nickname"=>"", "listing_size"=>"9.5", "listing_price"=>"160", "image_attachments_attributes"=>{"0"=>{"id"=>"1"}}}, "image_attachments"=>{"image"=>[#<ActionDispatch::Http::UploadedFile:0x00000109506810 #tempfile=#<Tempfile:/var/folders/vk/x5f3g8n147z_j39_mzkbfq600000gp/T/RackMultipart20140716-1370-63vlgx>, #original_filename="about.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"image_attachments[image][]\"; filename=\"about.png\"\r\nContent-Type: image/png\r\n">]}, "commit"=>"Submit", "id"=>"nike-air-max-90"}
[1m[35mListing Load (0.2ms)[0m SELECT "listings".* FROM "listings" WHERE "listings"."slug" = 'nike-air-max-90' ORDER BY "listings"."id" ASC LIMIT 1
[1m[36mUser Load (0.2ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1[0m
[1m[35m (0.1ms)[0m begin transaction
[1m[36mImageAttachment Load (0.1ms)[0m [1mSELECT "image_attachments".* FROM "image_attachments" WHERE "image_attachments"."listing_id" = ? AND "image_attachments"."id" IN (1)[0m [["listing_id", 2]]
[1m[35m (0.1ms)[0m commit transaction
Redirected to http://localhost:3000/listings/nike-air-max-90
Completed 302 Found in 5ms (ActiveRecord: 0.6ms)
Option 1 (Replace all existing attachments with new uploaded ones
In your update action, you are NOT doing what you are doing in create action. Which is this:
params[:image_attachments]['image'].each do |a|
#image_attachment = #listing.image_attachments.create!(:image => a, :listing_id => #listing.id)
end
You can't expect Rails to do this for you magically because this is not a typical use of accepts_nested_attributes feature. In fact, in your current code, you are not using this feature at all.
If you want to make it work with your current code, you will have to delete all existing image_attachments and create the new ones in the update action, like this:
def update
respond_to do |format|
if #listing.update(listing_params)
if params[:image_attachments] && params[:image_attachments]['image']
# delete existing image_attachments
#listing.image_attachments.delete_all
# create new ones from incoming params
params[:image_attachments]['image'].each do |a|
#image_attachment = #listing.image_attachments.create!(:image => a, :listing_id => #listing.id)
end
end
flash[:notice] = 'Deal was successfully updated.'
format.html { redirect_to #listing }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
This will replace all existing images with new ones, if you upload new ones.
Option 2 (Edit them individually)
If you want to be able to update existing attachments, you will have to modify the edit form to allow updating attachment records individually. Or do it via proper use of accepts_nested_attributes feature. Cocoon is one great gem help you incorporate nested attributes in your forms easily.
So I'm getting this error in one of my views and it seems to have to do with the way client is being initialized in the controller, here's the code for my Client model and controller:
Model:
class Client < ActiveRecord::Base
has_many :visits
has_many :exchanges, through: :visits
Controller:
class ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]
def index
#clients = Client.all
end
# GET /clients/new
def new
#client = Client.new
end
# POST /clients
# POST /clients.json
def create
#client = Client.new(client_params)
respond_to do |format|
if #client.save
format.html { redirect_to #client, notice: 'Client was successfully created.' }
format.json { render action: 'show', status: :created, location: #client }
else
format.html { render action: 'new' }
format.json { render json: #client.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /clients/1
# PATCH/PUT /clients/1.json
def update
respond_to do |format|
if #client.update(client_params)
format.html { redirect_to #client, notice: 'Client was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #client.errors, status: :unprocessable_entity }
end
end
end
# DELETE /clients/1
# DELETE /clients/1.json
def destroy
#client.destroy
respond_to do |format|
format.html { redirect_to clients_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_client
#client = Client.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def client_params
#hidden for security
end
end
So the error goes off at line 1 for my client form when it calls #client and says "undefined method `model_name' for ActiveRecord::Relation::ActiveRecord_Relation_Client:Class" Really could use some help as I have no idea what is going on, thanks.
Error Stack:
Started GET "/clients/new" for 127.0.0.1 at 2014-04-06 14:05:48 -0400
Processing by ClientsController#new as HTML
Rendered clients/_form.html.erb (62.2ms)
Rendered clients/new.html.erb within layouts/application (65.3ms)
Completed 500 Internal Server Error in 68ms
ActionView::Template::Error (undefined method `model_name' for ActiveRecord::Relation::ActiveRecord_Relation_Client:Class):
1: <%= simple_form_for(#client) do |f| %>
2: <% if #client.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#client.errors.count, "error") %> prohibited this client from being saved:</h2>
app/views/clients/_form.html.erb:1:in `_app_views_clients__form_html_erb___2200324505640086965_70348410359440'
app/views/clients/new.html.erb:3:in `_app_views_clients_new_html_erb___3059029162300151807_70348376263300'
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.6ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (12.8ms)