I am having trouble with Ajax file uploading in Rails 3.0.5 Ruby v 1.8.7 using the gem 'remotipart', '~> 0.4'. I have success with the alerts showing up when I remove the if #asset.save? statement in the controller but when its there the js file isn't called. For some reason the assets are not being saved.
Any ideas?
Controller:
def create
#asset = Asset.new(params[:asset])
respond_to do |format|
if #asset.save
format.html
format.js
end
end
end
View:
<%= form_for #asset, :remote => true, :html => {:multipart => true}, :id => "new_asset_form" do |f| %>
<%= render :partial => 'shared/error_messages', :locals => { :target => #asset } %>
<%= f.hidden_field :company_id, :value => current_company.id %>
<%= f.file_field :asset %>
<%= submit_tag 'Add', :class => 'submit' %>
<% end %>
Create.js.erb:
<%= remotipart_response do %>
// Display a Javascript alert
alert('success!');
<% if remotipart_submitted? %>
alert('submitted via remotipart')
<% else %>
alert('submitted via native jquery-ujs')
<% end %>
<% end %>
Terminal Log:
Started POST "/assets" for 127.0.0.1 at Thu May 10 14:45:40 -0400 2012
Processing by AssetsController#create as JS
Parameters: {"commit"=>"Add", "authenticity_token"=>"9TDxFQfTGrdz8gKti413FoIr1JUSwLGQQXv/tJQd+sY=", "utf8"=>"✓", "_"=>"", "asset"=>{"company_id"=>"5"}}
Company Load (0.5ms) SELECT `companies`.* FROM `companies` WHERE `companies`.`subdomain` = 'demo' LIMIT 1
User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 295 AND (company_id = 5) LIMIT 1
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 295 AND (company_id = 5) LIMIT 1
Rendered assets/create.js.erb (0.7ms)
Completed 200 OK in 182ms (Views: 8.9ms | ActiveRecord: 1.2ms)
Thanks for any help. Been stuck for hours.
Try upgrading to the latest version of Remotipart, found here: http://os.alfajango.com/remotipart/
Related
How can I use a conditional to do one thing if :name is passed to the _form and another thing if that :name isn't passed?
With :name passed:
Started GET "/inspirations/new?inspiration%5Bname%5D=Always+trust+yourself+more+than+you+doubt+yourself" for 127.0.0.1 at 2016-11-08 01:00:44 -0500
Processing by InspirationsController#new as HTML
Parameters: {"inspiration"=>{"name"=>"Always trust yourself more than you doubt yourself"}}
Without :name passed:
Started GET "/inspirations/new" for 127.0.0.1 at 2016-11-08 01:16:18 -0500
Processing by InspirationsController#new as */*
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
Inspiration Load (0.4ms) SELECT "inspirations".* FROM "inspirations" WHERE "inspirations"."id" IS NULL LIMIT 1
Rendered inspirations/_form.html.erb (4.1ms)
Rendered inspirations/new.html.erb within layouts/modal (5.9ms)
Completed 200 OK in 49ms (Views: 41.9ms | ActiveRecord: 0.7ms)
_form
<%= simple_form_for(#inspiration) do |f| %>
<%= f.text_area :name %>
<% if params[:name].nil? %> # Should Be Triggered If No :name Is Present in URL
etc...
<% end %>
<% end %>
So for example when a URL includes a string:
http://www.livetochallenge.com/inspirations/new?inspiration%5Bname%5D=Life+would+be+easier+if+I+had+the+source+code.
But I often use a URL shortener.
Didn't work for me:
Is there a way to check if part of the URL contains a certain string
including url parameters in if statement
Try this:
<%= simple_form_for(#inspiration) do |f| %>
<%= f.text_area :name %>
<% if params[:inspiration].try(:[], :name).nil? %> # Should Be Triggered If No :name Is Present in URL
etc...
<% end %>
<% end %>
This will check :name inside params[:inspiration] only if the later is present. So, no error should occur.
You can avoid the error using fetch.
<%= simple_form_for(#inspiration) do |f| %>
<%= f.text_area :name %>
<%= f.text_area :name %>
<% name = params.fetch(:inspiration, {}).fetch(:name, nil) %>
<% if name.nil? %>
etc...
<% end %>
<% end %>
I'm trying to update multiple records. The form generates fine and submits fine and the data is sent. The records are looked up to update, but no data is ever saved. I have my controller logic, form logic and console dump below. I'm trying to duplicate what Anthony Lewis put together but I have a feeling I am not passing the right data into or defining correctly the params.require().permit() method. Thanks in advance for your help!
class ConfigController < ApplicationController
def edit
#services = Service.all
end
def update
params["service"].keys.each do |id|
#service = Service.find(id.to_i)
#service.update_attributes!(service_params)
end
redirect_to config_url
end
private
def service_params
params.require(:service).permit(:id, :client_id, :client_secret)
end
end
Form code is:
<%= form_for :service, :url => update_config_path, :html => { :class => "form-horizontal", :method => "put", :remote => true } do %>
<% #services.each do |s| %>
<%= fields_for "service[]", s do |service_field| %>
<fieldset>
<legend><%= s.name %></legend>
<div class="form-group">
<%= service_field.label :client_id, "Consumer Key", :class => "col-sm-2 control-label" %>
<div class="col-sm-10">
<%= service_field.text_field :client_id, :class => "form-control" %>
</div>
</div>
<div class="form-group">
<%= service_field.label :client_secret, "Consumer Secret", :class => "col-sm-2 control-label" %>
<div class="col-sm-10">
<%= service_field.text_field :client_secret, :class => "form-control" %>
</div>
</div>
</fieldset>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
Console reads:
Started PUT "/config" for 127.0.0.1 at 2013-11-22 15:44:08 -0800
Processing by ConfigController#update as JS
Parameters: {"utf8"=>"✓", "service"=>{"1"=>{"client_id"=>"testid", "client_secret"=>"testsecret"}, "2"=>{"client_id"=>"testkey", "client_secret"=>""}, "3"=>{"client_id"=>"", "client_secret"=>""}}, "commit"=>"Save changes"}
Service Load (0.3ms) SELECT "services".* FROM "services" WHERE "services"."id" = $1 LIMIT 1 [["id", 1]]
Unpermitted parameters: 1, 2, 3
(0.1ms) BEGIN
(0.1ms) COMMIT
Unpermitted parameters: 1, 2, 3
{}
Service Load (0.2ms) SELECT "services".* FROM "services" WHERE "services"."id" = $1 LIMIT 1 [["id", 2]]
Unpermitted parameters: 1, 2, 3
(0.1ms) BEGIN
(0.1ms) COMMIT
Unpermitted parameters: 1, 2, 3
{}
Service Load (0.2ms) SELECT "services".* FROM "services" WHERE "services"."id" = $1 LIMIT 1 [["id", 3]]
Unpermitted parameters: 1, 2, 3
(0.1ms) BEGIN
(0.1ms) COMMIT
Unpermitted parameters: 1, 2, 3
{}
Redirected to http://localhost:3000/config
Completed 302 Found in 6ms (ActiveRecord: 1.1ms)
I found a solution, but perhaps it isn't the best. Let me know if someone has a better idea and I'd be happy to try it!
In the solution I updated my controllers update action and the service_params.
I passed id to service_params and called fetch method on the require method to get the correct params. I noticed that in the console it read Unpermitted parameters: 1, 2, 3 when it was saving each record indicating the params were an array and I also noticed in #Vijay's solution he tried to narrow down the params as well. After some Googling and console logging I came up with the code below.
def update
params["service"].keys.each do |id|
#service = Service.find(id.to_i)
#service.update_attributes!(service_params(id))
end
redirect_to config_url
end
def service_params(id)
params.require(:service).fetch(id).permit( :client_id, :client_secret )
end
What do you think?
Try this...
params.require(:service).permit( id: [ :client_id, :client_secret ] )
Your strong parameters line should be
params.require(:service).permit( [:id, :client_id, :client_secret ] )
This permits arrays of values
http://guides.rubyonrails.org/action_controller_overview.html#more-examples
Try this one and it will work.
Let me know if you get any issue
def service_params
params.require(:service).map do |_, p|
p.permit(:id, :client_id, :client_secret)
end
end
http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html
Please try:
def update
Service.update(service_params.keys, service_params.values
end
def service_params
params.permit(service: [:client_id, :client_secret]).require(:service)
end
I'm creating a profile that is associated with a member id based on Devise authentication.
When creating the profile, the values aren't inserted into the database.
Routes file.
resources :troopers do
resource :trooper_profile
end
Trooper model
has_one :trooper_profile
Trooper Profile model
belongs_to :trooper
Trooper Controller #create action
def create
#trooper = current_trooper
#profile = #trooper.build_trooper_profile(params[:profile])
respond_to do |format|
if #profile.save
format.html { redirect_to(trooper_trooper_profile_path, :notice => 'Profile was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
Profile Form
<%= form_for #profile, :url => trooper_trooper_profile_path(#trooper) do |f| %>
<%= f.label :first_name %><br />
<%= f.text_field :first_name %><br /><br />
<%= f.label :last_name %><br />
<%= f.text_field :last_name %><br /><br />
<p><%= submit_tag "Create Profile" %></p>
<% end %>
Server output
Started POST "/troopers/1/trooper_profile" for 127.0.0.1 at 2011-05-20 13:04:01 +1000
Processing by TrooperProfilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LhT6b4xu5bIJ5kwhS74L7dpaGbuR5BTdirh9AziD+Ew=", "trooper_profile"=>{"first_name"=>"Robert", "last_name"=>"", "commit"=>"Create Profile", "trooper_id"=>"1"}
Trooper Load (0.5ms) SELECT "troopers".* FROM "troopers" WHERE ("troopers"."id" = 1) LIMIT 1
TrooperProfile Load (0.3ms) SELECT "trooper_profiles".* FROM "trooper_profiles" WHERE ("trooper_profiles".trooper_id = 1) LIMIT 1
Rendered trooper_profiles/_form.html.erb (11.7ms)
Rendered shared/_head.html.erb (1.6ms)
Rendered shared/_menutop.html.erb (1.2ms)
Rendered trooper_profiles/new.html.erb within layouts/application (18.5ms)
Completed 200 OK in 109ms (Views: 22.5ms | ActiveRecord: 0.8ms)
I've got this same setup in another application and can't see why this isn't working.
Change the following...
#profile = #trooper.build_trooper_profile(params[:trooper_profile])
It appears the parameters being passed are :trooper_profile
trooper_profile"=>{"first_name"=>"Robert", "last_name"=>"", "commit"=>"Create Profile", "trooper_id"=>"1"}
However, you're referencing :profile
If it's rendering the new view, then the profile isn't saving - perhaps it's a validation error? Does TrooperProfile require a last name (blank in your example)?
I have this form that I want to load via AJAX into the video show view:
<%= form_for #video, :url => {:action => "update"}, :remote => true do |f| %>
<div class="field">
<%= f.text_field :topic_names, :class => "topic_field" %>
</div>
<%= f.submit "Add Topic" %>
<% end %>
I have this link in the video show view that when clicked, I want it to render the form:
<%= link_to "Add Topics", new_topicable_path(#topicable, :format => :js), :remote => true, :id => 'edit_topics_link' %>
I put the form in topicables/new.html.erb and I have topicables/new.js.erb file which has:
$("<%= escape_javascript render(:file => 'topicables/new.html.erb') %>").insertAfter('.topic_holder');
$('#edit_topics_link').hide();
Now when I click the link, I get an error in my logs. This is what my logs show:
Started GET "/topicables/new.js" for 127.0.0.1 at Sat Apr 02 03:58:52 -0700 2011
Processing by TopicablesController#new as JS
Rendered topicables/new.html.erb (0.7ms)
Rendered topicables/new.js.erb (2.6ms)
Completed in 15ms
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: <%= form_for #video, :url => {:action => "update"}, :remote => true do |f| %>
2: <div class="field">
3: <%= f.text_field :topic_names, :class => "topic_field" %>
4: </div>
app/views/topicables/new.html.erb:1:in `_app_views_topicables_new_html_erb___1876131309_2172772700_0'
app/views/topicables/new.js.erb:1:in `_app_views_topicables_new_js_erb__1367015167_2172792200_0'
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (92.5ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (98.9ms)
What's going on? How can I fix this error to make the AJAX rendering of the form work?
This is basically telling you that #video is not defined. If that's the case you can either define it in your new method or use :video which creates a new instance variable rather than looking for one in the page context. Then you can handle the find and update in the update method.
Edit: jQuery load method
$("#myButton").click(function(){
$("#target").load("/topicables/new #new_topicable");
});
I have the following form:
<%=form_for [:project, #permission], :url => { :action => "update" } do |f| %>
<% roles = Role.all %>
Role: <%= f.collection_select :role_id, roles, :id, :name, :prompt => true %>
<%=f.submit "Send Request" %>
<%=f.hidden_field :user_id %>
<% end %>
In my controller I have:
def update
#permission = Permission.find_by_user_id(params[:user_id])
.
.
.
end
** What I want to do is update the role_id,,,, so I need the above to find the permission record... Problem is,,, params[:user_id] is coming back null?
Am I missing something? thanks
Update
Here is the error and request params, which show the vars are there?
Started POST "/projects/3/permissions/useronproject" for 127.0.0.1 at Thu Oct 14 12:17:12 -0700 2010
Processing by PermissionsController#update as HTML
Parameters: {"commit"=>"Send Request", "authenticity_token"=>"KJ2C20MzTJ8VQV0NiNzOr357QKV5hWjeuazOBcS5iPU=", "utf8"=>"✓", "id"=>"useronproject", "permission"=>{"role_id"=>"1", "user_id"=>"11"}, "project_id"=>"3"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
Permission Load (0.1ms) SELECT "permissions".* FROM "permissions" WHERE ("permissions"."user_id" IS NULL) LIMIT 1
see - user_id is NULL?
user_id is further down the params hash. Try:
params[:permission][:user_id]