Trouble splitting output of multiselect in Rails - ruby-on-rails

I have a multiselect (using bootstrap-multiselect) in my #minisets new form that aims to associate #scales with the #miniset via the #sizes table.
The associations work fine. What I'm stuck on is how to loop through the multiple :scale_id submissions from the multiselect and create lines in the #sizes table for them all.
Following this answer I have been trying to use split and then loop the create but I think the fact that that answer pertains to a HABTM relationship and mine is has_many_through means I need a different solution?
In my minisets controller I have
def new
#miniset = Miniset.new
#miniset.sizes.build
end
def create
#miniset = Miniset.new(miniset_params)
if #miniset.save
params[:scale_id].split(',').each do |id|
#miniset.sizes.create(params[:sizes_attributes])
end
redirect_to #miniset
else
render 'new'
end
end
private
def miniset_params
params.require(:miniset).permit(:name, :release_date, :material, :pcode, :notes, :quantity, :random, productions_attributes: [:id, :manufacturer_id, :miniset_id], sizes_attributes: [:id, :scale_id, :miniset_id], sculptings_attributes: [:id, :sculptor_id, :miniset_id])
end
end
In my view I have
<%= f.fields_for :sizes do |size_fields| %>
<%= size_fields.label :scale_id, simple_pluralize(#miniset.scales.count, 'Scale') %>
<%= size_fields.select :scale_id,
options_from_collection_for_select(Scale.all, :id, :name, #miniset.scales.map(&:id)),
{},
{class: 'multiselect', multiple: true} %>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
$('.multiselect').multiselect();
});
</script>
I'm currently getting error undefined methodsplit' for nil:NilClass` when I submit.
I think that may be because the log shows an empty scale_id passed before the two filled ones and split won't accept nil? Here is the log when submitting TWO scales.
Started POST "/minisets" for 127.0.0.1 at 2014-01-30 10:49:59 +0000
Processing by MinisetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"R0RxDMwB5/ytSb5qgjIlVR5as0/DTkstgFMDXcefDnc=", "miniset"=>{"name"=>"Test for size", "quantity"=>"10", "random"=>"0", "material"=>"Hard Plastic", "sizes_attributes"=>{"0"=>{"scale_id"=>["", "1", "5"]}}, "pcode"=>"", "release_date(1i)"=>"", "release_date(2i)"=>"", "release_date(3i)"=>"", "notes"=>""}, "Set Scale"=>{"#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Size:0x007fcf643c29f0>"=>""}, "commit"=>"Add set"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'd59f28d384d62b71719dd845b4e5353cdd993016' LIMIT 1
Unpermitted parameters: scale_id
SQL (0.9ms) INSERT INTO "minisets" ("created_at", "material", "name", "notes", "pcode", "quantity", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["material", "Hard Plastic"], ["name", "Test For Size"], ["notes", ""], ["pcode", ""], ["quantity", 10], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
SQL (0.6ms) INSERT INTO "sizes" ("created_at", "miniset_id", "updated_at") VALUES (?, ?, ?) [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["miniset_id", 41], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
(4.2ms) commit transaction
Completed 500 Internal Server Error in 153ms
NoMethodError (undefined method `split' for nil:NilClass):
app/controllers/minisets_controller.rb:19:in `create'
I'm sure what I have after the split is incorrect but I can't play with it until the split works. I can get rid of the error by adding to_s before the split but I get no better results.
Been making very slow progress on this multiselect for days now so any help very much appreciated.

Thanks to this fantastic youtube video I solved my problem.
My form:
<%= f.fields_for(#size) do |sf| %>
<%= sf.label simple_pluralize(#miniset.scales.count, 'Scale') %>
<%= collection_select( :scales, :id, #all_scales, :id, :name,
{},
{class: 'multiselect', multiple: true}) %>
<% end %>
In my minisets_controller I have the following new and create actions:
def new
#miniset = Miniset.new
#all_scales = Scale.all
#size = #miniset.sizes.build
end
def create
#miniset = Miniset.new(miniset_params)
params[:scales][:id].each do |scale|
if !scale.empty?
#miniset.sizes.build(:scale_id => scale)
end
end
if #miniset.save
redirect_to #miniset
else
render 'new'
end
end
It works perfectly. If anyone else is having the same problem, trying to get multiselects to work in rails with has_many_through, I recommend watching that video. So pleased.

Related

Bad response from server after tinymce image upload

I'm trying to upload images using paperclip and tinymce-rails-image-upload following this demo. I'm uploading images in a question model (that belongs to comments). When I upload, I get a 'got a bad response from the server' message and the image isn't shown in the editor, however it does create a new question.
Here is my the log after upload:
Processing by TinymceAssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"auth token", "hint"=>"", "file"=>#<ActionDispatch::Http::UploadedFile:0x000001025a2780 #tempfile=# <File:/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207- 12522-9rj6xq>, #original_filename="applecash.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"applecash.jpg\"\r\nContent-Type: image/jpeg\r\n">, "alt"=>""}
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207-12522-9rj6xq[0]' 2>/dev/null
Unpermitted parameters: utf8, authenticity_token
(0.1ms) begin transaction
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE (questions.position IS NOT NULL) AND (1 = 1) ORDER BY questions.position DESC LIMIT 1
Binary data inserted for `string` type on column `file_content_type`
SQL (0.8ms) INSERT INTO "questions" ("created_at", "file_content_type", "file_file_name", "file_file_size", "file_updated_at", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["file_content_type", "image/jpeg"], ["file_file_name", "timcook.jpg"], ["file_file_size", 120040], ["file_updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["position", 9], ["updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00]]
(7.3ms) commit transaction
Completed 200 OK in 68ms (Views: 0.6ms | ActiveRecord: 8.7ms)
Here is the tinymce controller:
class TinymceAssetsController < ApplicationController
respond_to :json
def create
geometry = Paperclip::Geometry.from_file params[:file]
question = Question.create params.permit(:file, :alt, :hint)
render json: {
question: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"
end
end
The questions controller create action looks like this (do I add #comment and the additional parameters to the tinymce controller?):
def create
#comment = Comment.find(params[:comment_id])
#question = #comment.questions.new(question_params)
end
...
def question_params
params.require(:question).permit(:body, :comment_id, :user_id, :file, :position)
end
The question model:
class Question < ActiveRecord::Base
has_attached_file :file
end
and the editor view:
<%= simple_form_for [#comment, Question.new] do |f| %>
<%= f.text_area :body, :class => "tinymce", :rows => 10, :cols => 60 %>
<% end %>
<%= tinymce plugins: ["uploadimage"] %>
I'm confused as to why its creating a new question for every uploaded image and what's still causing the 'bad response' error.
it seems tinymce-rails-imageupload expects "image" in response to uploaded file
render json: {
image: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"

Unpermitted parameters when uploading image with tinymce

I'm using tinymce-rails-image-upload to upload images with paperclip (following this demo-app). When I try to upload an image I'm getting an 'umpermitted parameters' reminder and the image doesn't upload. The upload modal shows 'Got a bad response from server':
Processing by TinymceAssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"auth token", "hint"=>"", "file"=>#<ActionDispatch::Http::UploadedFile:0x000001025a2780 #tempfile=# <File:/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207- 12522-9rj6xq>, #original_filename="applecash.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"applecash.jpg\"\r\nContent-Type: image/jpeg\r\n">, "alt"=>""}
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207-12522-9rj6xq[0]' 2>/dev/null
Unpermitted parameters: utf8, authenticity_token
(0.1ms) begin transaction
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE (questions.position IS NOT NULL) AND (1 = 1) ORDER BY questions.position DESC LIMIT 1
Binary data inserted for `string` type on column `file_content_type`
SQL (0.8ms) INSERT INTO "questions" ("created_at", "file_content_type", "file_file_name", "file_file_size", "file_updated_at", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["file_content_type", "image/jpeg"], ["file_file_name", "timcook.jpg"], ["file_file_size", 120040], ["file_updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["position", 9], ["updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00]]
(7.3ms) commit transaction
Completed 200 OK in 68ms (Views: 0.6ms | ActiveRecord: 8.7ms)
Here's the controller:
class TinymceAssetsController < ApplicationController
respond_to :json
def create
geometry = Paperclip::Geometry.from_file params[:file]
question = Question.create params.permit(:file, :alt, :hint)
render json: {
question: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"
end
end
and the question model:
class Question < ActiveRecord::Base
has_attached_file :file
end
and the view:
<%= simple_form_for [#comment, Question.new] do |f| %>
<%= f.text_area :body, :class => "tinymce", :rows => 10, :cols => 60 %>
<% end %>
<%= tinymce plugins: ["uploadimage"] %>
It's ok to not permit some of the parameters, so Unpermitted parameters: utf8, authenticity_token is a reminder, not an exception. I suggest you log what are question model instance errors:
question = Question.create params.permit(:file, :alt, :hint)
logger.debug question.errors.full_messages
May be wrong, but, you have the following:
question = Question.create params.permit(:file, :alt, :hint)
I think you'd just make that read like this and it would work:
question = Question.create params.permit(:file, :alt, :hint, :utf8, :authenticity_token)
The error is clear. You have not permitted those parameters. But they exist. You expressly permit the other three there so I presume you have to permit those two additional.
That's my guess and I'm sticking to it :).

Saving a collection of objects rails 4 (strong params)

I am currently working on the backend of shop. The Client wants to be able to see a list of all products and update the stock values for all the products in one submission of a form. I have a working solution, but it's a very 'hacky' and introduces a lot of issues. I am new to Ruby on Rails and web development in general so I'm still learning a few of the fundamental conventions and what not.
I will paste my working solution and then attempt to explain the problem I have:
class Product < ActiveRecord::Base
has_many :stocks
...
end
class Stock < ActiveRecord::Base
belongs_to :product
...
end
stock_controller.rb
class StocksController < ApplicationController
def index
#products = Product.all.includes(:stocks)
end
...
def update_current
#stock_params = params[:stock]
#stock_params.each do |stock_params|
params.permit(:current_stock, :product_id)
#stock = Stock.new(stock_params)
#stock.save
end
redirect_to stocks_path, notice: 'Stocks were successfully updated'
end
...
stocks.index.html.erb
...
<%= form_tag url_for(:action => 'update_current') do |f| %>
<% #products.each do |product| %>
<tr>
<td><%= product.product_name %></td>
<td><%= product.minimum_stock %></td>
<td><%= text_field_tag "stock[][current_stock]", product.stocks.last.current_stock %></td>
<%= hidden_field_tag "stock[][product_id]", product.stocks.last.product_id %>
</tr>
<% end %>
<%= submit_tag 'save' %>
<% end %>
...
When I hit the submit button params set is as it needs to be:
console :
Started POST "/stocks/update_current" for 127.0.0.1 at 2013-10-24 11:54:03 +0100
Processing by StocksController#update_current as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NlabBuwI06t+YN5O6p7dm+Zg2Bwc9uXrKUdWaBqNs9w=", "stock"=>[{"current_stock"=>"1", "product_id"=>"1"}, {"current_stock"=>"2", "product_id"=>"2"}, {"current_stock"=>"3", "product_id"=>"24"}, {"current_stock"=>"4", "product_id"=>"25"}, {"current_stock"=>"5", "product_id"=>"23"}, {"current_stock"=>"6", "product_id"=>"21"}, {"current_stock"=>"7", "product_id"=>"19"}, {"current_stock"=>"8", "product_id"=>"22"}, {"current_stock"=>"9", "product_id"=>"5"}], "commit"=>"save"}
Unpermitted parameters: utf8, authenticity_token, stock, commit
(0.2ms) BEGIN
SQL (136.6ms) INSERT INTO "stocks" ("created_at", "current_stock", "product_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00], ["current_stock", 1], ["product_id", 1], ["updated_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00]]
(24.2ms) COMMIT
Unpermitted parameters: utf8, authenticity_token, stock, commit
(0.2ms) BEGIN
SQL (0.7ms) INSERT INTO "stocks" ("created_at", "current_stock", "product_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00], ["current_stock", 2], ["product_id", 2], ["updated_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00]]
(0.7ms) COMMIT
Unpermitted parameters: utf8, authenticity_token, stock, commit
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "stocks" ("created_at", "current_stock", "product_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00], ["current_stock", 3], ["product_id", 24], ["updated_at", Thu, 24 Oct 2013 10:54:03 UTC +00:00]]
(0.6ms) COMMIT
As you can see form the log the authenticity_token, and other params are unpermitted. Now I understand the purpose of the token and the other params, what I do not know, why exactly I am running into this issue.
My guess is the way I am permitting the params. I don't get how to tell strong_params to permit an array of hashes: stock => [{:current_stock, :product_id},{:current_stock, :product_id}, ..., ....]. params.permit(stock: [:current_stock, :product_id]) ???
It doesn't make sense in this case to nest stocks under product, as I am working with a collection of products opposed to a single product.
In an ideal world, I would like to be able to insert the new stock values for all products in one submit and save to the database with one query. I feel as if Ajax may be a viable solution, but again, until I fully understand whats going on I don't want to confuse things even more.
Any solutions or advice is much appreciated. I hope the above makes sense! It's very difficult to articulate these things sometimes.
This may or may not be your problem, but in your update_current method, shouldn't it be stock_params.permit(:current_stock, :product_id) ? Also a minor point, why do you have |f| in your form_tag if you don't use it.

Rails 4 nested resource hash not committed to database

This is my first app in Rails 4, but I'm not sure whether Rails 4 is the problem.
I have nested resources as follows:
resources :made_games do
resources :made_game_instances
end
When I try to save a new made_game_instance this is what's happening in the log:
Started POST "/made_games/11/made_game_instances" for 127.0.0.1 at 2013-09-10 12:03:55 -0700
Processing by MadeGameInstancesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jEN2syjftjRtf3DBnijtp7gNVUEFrI+HYTUs+HFgo5M=", "made_game_instance"=>{"new_word1"=>"bluesky"}, "commit"=>"Create Made game instance", "made_game_id"=>"11"}
MadeGame Load (122.7ms) SELECT "made_games".* FROM "made_games" WHERE "made_games"."id" = $1 LIMIT 1 [["id", "11"]]
(14.0ms) BEGIN
SQL (215.9ms) INSERT INTO "made_game_instances" ("created_at", "made_game_id", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00], ["made_game_id", 11], ["updated_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00]]
(5.7ms) COMMIT
Redirected to http://localhost:3000/made_games/11/made_game_instances/5
Completed 302 Found in 458ms (ActiveRecord: 358.3ms)
You can see that the params hash contains the hash where the new_game_instance attribute :new_word1 is assigned the value "bluesky." What I cannot figure out is why this assignment does not appear in the SQL that is subsequently generated when the new 'made_game_instances' object is created.
Additional information
Since this is Rails 4, in order to whitelist all the parameters (at least at this stage in development), I have used permit! in the params private method at the bottom of the controllers for both made_games and made_game_instances.
The made_games controller:
class MadeGamesController < ApplicationController
def new
#made_game = MadeGame.new
end
def create
#made_game = MadeGame.new(made_game_params)
if #made_game.save
flash[:notice] = "Here you go!"
redirect_to #made_game
else
flash[:notice] = "Something about that didn't work, unfortunately."
render :action => new
end
end
def show
#made_game = MadeGame.find(params[:id])
end
private
def made_game_params
params.require(:made_game).permit!
end
end
Here is a link to the github repo: https://github.com/keb97/madlibs/tree/users_making
The form used to create a new made_game_instance is:
<%= simple_form_for [#made_game, #made_game_instance] do |f| %>
<p>
<%= f.input :new_word1, label: #made_game.word1.to_s %>
</p>
<%= f.button :submit %>
<% end %>
I should also note that there is one form for made_game, and a separate form for made_game_instance, rather than a nested form, so I do not believe this is an issue of accepts_nested_attributes_for or fields_for.
In your made_games_instance_controller.rb
this line...
#made_game_instance = #made_game.made_game_instances.build(params[:made_game_instance_params])
should actually be...
#made_game_instance = #made_game.made_game_instances.build(made_game_instance_params)
There is no params hash entry with a symbol key :made_game_instance_params

Create then Update - Rails

I have a set of parameters below that are submitted through a form
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>"yahoo.com "}, "type"=>"html", "original_url"=>"http://yahoo.com", "url"=>"http://www.yahoo.com/", "title"=>"Yahoo!", "description"=>"Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information.", "favicon_url"=>"http://www.yahoo.com/favicon.ico", "provider_url"=>"http://www.yahoo.com", "provider_display"=>"www.yahoo.com", "provider_name"=>"Yahoo", "safe"=>"true", "html"=>"", "thumbnail_url"=>"", "object_type"=>"link", "image_url"=>"", "category_id"=>"1"}
I want to create a new "links" record in the links model, which belongs to the categories model. My "create" action in the links controller looks like this
def create
#category = Category.find_by_id(params[:category_id])
#link = #category.links.build(params[:link])
#link.user_id = current_user.id
respond_to do |format|
if #link.save
links_attributes = params.slice(:original_url, :title, :description, :favicon_url, :provider_url, :provider_display, :thumbnail_url, :object_type)
#link.update_attributes(links_attributes)
else
end
end
end
If I just did #link.save without the update attributes, it only saves comment, url and category id. However, the above creates 2 records, one comment, url and category_id and another with all of the data.
How can I make sure this creates just one record, with all of the information?
UPDATE
If I could just create the record with the 3 parameters, then update it with the remaining parameters (links_attributes), I would be fine with that...just not sure how to do it.
This is the output I get when submitting:
Started POST "/categories/1/links" for 127.0.0.1 at 2013-01-11 12:43:44 -0500
Processing by LinksController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>"bloomberg.com "}, "type"=>"html", "original_url"=>"http://bloomberg.com", "url"=>"http://www.bloomberg.com/", "title"=>"Business, Financial & Economic News, Stock Quotes", "description"=>"Bloomberg is a premier site for business and financial market news. It delivers world economic news, stock futures, stock quotes, & personal finance advice.", "favicon_url"=>"http://www.bloomberg.com/favicon.ico", "provider_url"=>"http://www.bloomberg.com", "provider_display"=>"www.bloomberg.com", "provider_name"=>"Bloomberg", "safe"=>"true", "html"=>"", "thumbnail_url"=>"http://www.bloomberg.com/image/is2KySnyVWmA.jpg", "object_type"=>"link", "image_url"=>"", "category_id"=>"1"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "links" ("category_id", "comment", "created_at", "description", "favicon_url", "object_type", "original_url", "points", "profile_link", "provider_display", "provider_url", "thumbnail", "thumbnail_url", "title", "updated_at", "url", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["category_id", "1"], ["comment", ""], ["created_at", Fri, 11 Jan 2013 17:43:
Started POST "/categories/1/links" for 127.0.0.1 at 2013-01-11 12:43:44 -0500
Processing by LinksController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>""}, "commit"=>"Post", "category_id"=>"1"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.4ms) INSE44 UTC +00:00], ["description", "Bloomberg is a premier site for business and financial market news. It delivers world economic news, stock futures, stock quotes, & personal finance advice."], ["favicon_url", "http://www.bloomberg.com/favicon.ico"], ["object_type", "link"], ["original_url", "http://bloomberg.com"], ["points", nil], ["profile_link", nil], ["provider_display", "www.bloomberg.com"], ["provider_url", "http://www.bloomberg.com"], ["thumbnail", nil], ["thumbnail_url", "http://www.bloomberg.com/imRT INTO "links" ("category_id", "comment", "created_at", "description", "favicon_url", "object_type", "original_url", "points", "profile_link", "provider_display", "provider_url", "thumbnail", "thumbnail_url", "title", "updated_at", "url", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["category_id", "1"], ["comment", ""], ["created_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["description", nil], ["favicon_url", nil], ["object_type", nil], ["original_url", nil], ["points", nil], ["profile_link", nil], ["provider_display", nil], ["provider_url", nil], ["thumbnail", nil], ["thumbnail_url", nil], ["title", nil], ["updated_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["url", ""], ["user_id", 1]]
(1.1ms) commit transaction
Rendered links/create.js.erb (0.0ms)
Completed 200 OK in 8ms (Views: 3.9ms | ActiveRecord: 1.6ms)
age/is2KySnyVWmA.jpg"], ["title", "Business, Financial & Economic News, Stock Quotes"], ["updated_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["url", "bloomberg.com "], ["user_id", 1]]
(2.5ms) commit transaction
Rendered links/create.js.erb (0.0ms)
This is my form:
<%= form_for([#category, #category.links.build], :remote => true, :class => "form-horizontal") do |f| %>
<%= f.hidden_field :category_id, :value => params[:id] %>
Comment: <%= f.text_field :comment %><BR>
Link: <%= f.text_field :url %>
<%= f.submit "Post", :class => "btn", :disable_with => '...', :id => "new_link_button" %>
<% end %>
<div class="selector" style="width:350px;margin:-30px 0px 0px 0px;"></div>
<!-- Placeholder that tells Preview where to put the loading icon-->
<div class="loading">
<img src='http://embedly.github.com/jquery-preview/images/loading-rectangle.gif'>
</div>
<script>
$('#link_url').preview({ key:'60f1dcdf3258476794784148a6eb65e7', // Sign up for a key: http://embed.ly/pricing
selector : {type:'rich'},
preview : {
submit : function(e, data){
$.ajax({
dataType: 'script',
url: this.form.attr('action'),
type: 'POST',
data: data
});
},
},
autoplay : 0,
maxwidth : 350,
display : {display : 'rich'}
});
$('#new_link_button').click(function(e) {
e.preventdevault();
$('.new_link').submit();
return false;
});
</script>
This is my routes:
resources :categories, :only => [:new, :show, :create, :edit, :update] do
resources :links, :only => [:new, :show, :create, :edit, :update]
resources :industries, :only => [:new, :show, :create, :edit, :update]
resources :territories, :only => [:new, :show, :create, :edit, :update]
end
Try setting them before save.
def create
#link = Link.new(params[:link])
#link.category_id = params[:category_id]
#link.original_url = params[:original_url]
#link.title = params[:title]
#link.description = params[:description]
#link.user_id = current_user.id
# etc...
respond_to do |format|
if #link.save
# do things...
else
# do other things...
end
end
end
I think there's a problem with how your form is being constructed. As you can see in your posted parameters, params[:link] only includes a subset of the data you are trying to save on link:
"link"=>{"category_id"=>"1", "comment"=>"", "url"=>"yahoo.com "}
The rest is all at the top level of the params array:
Parameters: {... "original_url"=>"http://yahoo.com", "url"=>"http://www.yahoo.com/", "title"=>"Yahoo!", "description"=>"Welcome to Yahoo!..." ...}
You should look at how you're using form_for to construct your form, and make sure it's being used correctly for the additional parameters.
Edit:
If you can't edit the form, then you could do this in your controller:
#link.user_id = current_user.id
links_attributes = params.slice(:original_url, :title, :description, :favicon_url, :provider_url, :provider_display, :thumbnail_url, :object_type)
#link.attributes = links_attributes
respond_to do |format|
if #link.save
...
First of all, you don't need to call #link.save then #link.update_attributes, because #link.update_attributes would save #link in your db if it is not already there.
From the logs you posted, it seems your controller receives two post requests, this is why it creates two objects, I think the reason, is that two submits happen:
one by the form that is submitted and the other one by the ajax request inside your $('#link_url').preview(... code.

Resources