I want to use find_or_create method in my game dates controller. I don't know how to use that method in create action, when params are in game_date_params. Any suggestion how can I extract date from game_date_params?
class GameDatesController < ApplicationController
before_action :authenticate_user!
before_action :authenticate_admin
def index
#game_dates = GameDate.all
#showcases = Showcase.joins(:game_dates)
end
def new
#game_date = GameDate.new
#game_date.referee_stats.build
end
def create
#game_date = GameDate.new(game_date_params)
if #game_date.save
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
def show
#game_date = GameDate.find(params[:id])
end
def destroy
#game_date = GameDate.find(params[:id]).destroy
redirect_to root_url
flash[:success] = "Game date deleted"
end
private
def game_date_params
params.require(:game_date).permit(:date, referee_stats_attributes: [ :games_count, :showcase_id ])
end
This is output from POST action:
Started POST "/game_dates" for 127.0.0.1 at 2016-04-01 10:21:44 +0200
Processing by GameDatesController#create as HTML Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"jmuOmMCO/WTFIkxrsw5l2cPVMqZAl7h11f281I+OyoHH3ddwKoB9ANAqvQEHulR88c7fzQXnnIaxs8FChMCjqw==",
"game_date"=>{"date(1i)"=>"2016", "date(2i)"=>"4", "date(3i)"=>"1",
"referee_stats_attributes"=>{"0"=>{"games_count"=>"4",
"showcase_id"=>"1"}}}, "commit"=>"Create Game date"} User Load
(0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER
BY "users"."id" ASC LIMIT 1 [["id", 1]] GameDate Load (0.4ms)
SELECT "game_dates".* FROM "game_dates" WHERE "game_dates"."date" IS
NULL LIMIT 1 (0.2ms) BEGIN SQL (0.4ms) INSERT INTO "game_dates"
("date", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING
"id" [["date", "2016-04-01"], ["created_at", "2016-04-01
08:21:44.864669"], ["updated_at", "2016-04-01 08:21:44.864669"]] SQL
(0.4ms) INSERT INTO "referee_stats" ("games_count", "showcase_id",
"game_date_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4,
$5) RETURNING "id" [["games_count", 4], ["showcase_id", 1],
["game_date_id", 7], ["created_at", "2016-04-01 08:21:44.866897"],
["updated_at", "2016-04-01 08:21:44.866897"]] (18.1ms) COMMIT
Redirected to http://localhost:3000/showcases Completed 302 Found in
31ms (ActiveRecord: 20.1ms)
GameDate.find_or_create_by(game_date_params) would find record with ALL game_date_params, so you could do this by finding with specific params like date and assign rest of attributes to it via block. for example:
def create
# find or initialize the record
#game_date = GameDate.find_or_initalize_by(date: game_date_params[:date]) do |game_date|
# Accept nested attributes as well
game_date.assign_attributes(game_date_params)
end
if #game_date.save
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
See also: find_or_create_by and AttributesAssignment API docs
It should be like :
def create
#game_date = GameDate.find_or_create_by(game_date_params)
if #game_date.present?
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
Create action is for creating an object after the new action has been called and update action if the same but for edit. Mixing create & update logic i not a good idea. Maybe you should rethink what are you trying to do in your views.
Related
I have a problem with my small app build in Rails 5.
The project have only 4 tables: User, Custom, Contact, ContactCustom
The idea is an User register his customs fields and when he is going to add new contacts, the form should show the customs of the User logged in.
My problem is when I try to register a new contact with the customs of the user logged in, I have a n+1 inserting a nil register in ContactCustom table and don't catch the custom_id that I pass with a hidden_field.
My models are like this:
class Custom < ApplicationRecord
belongs_to :user
belongs_to :kind
has_many :contact_customs
has_many :contacts, through: :contact_customs
end
class ContactCustom < ApplicationRecord
belongs_to :contact, optional: true
belongs_to :custom, optional: true
accepts_nested_attributes_for :custom
end
class Contact < ApplicationRecord
belongs_to :user
has_many :contact_customs
has_many :customs, through: :contact_customs
accepts_nested_attributes_for :contact_customs
end
and here my contact_controller:
class ContactsController < ApplicationController
before_action :set_contact, only: [:show, :edit, :update, :destroy]
before_action :set_user_and_custom, only: [ :new, :create, :edit ]
def index
#contacts = Contact.all
end
def show
end
def new
#contact = Contact.new
#contact.contact_customs.build
end
def edit
end
def create
#contact = Contact.new(contact_params)
#contact.contact_customs.build
#binding pry
respond_to do |format|
if #contact.save
format.html { redirect_to #contact, notice: 'Contact was successfully created.' }
format.json { render :show, status: :created, location: #contact }
else
format.html { render :new }
format.json { render json: #contact.errors, status: :unprocessable_entity }
end
end
end
private
def set_contact
#contact = Contact.find(params[:id])
end
def set_user_and_custom
#user = current_user
#usercustom = Custom.where(user_id: #user)
end
def contact_params
params.require(:contact).permit(:email, :name, :user_id,
contact_customs_attributes: [ :id, :value, :custom_id, custom_attributes: [] ])
end
end
and here is my form ... I think that I made something wrong with the each loop:
<% #usercustom.each do |c| %>
<%= f.fields_for :contact_customs do |cc| %>
<div class="field">
<%= cc.label :value, c.name %>
<%= cc.text_field :value %>
</div>
<%= cc.fields_for :custom do |custom| %>
<%= custom.text_field :id, value: c.id %>
<% end %>
<% end %>
<% end %>
I don't know how to show how many custom fields as necessary without this loop and my query ~> #usercustom = Custom.where(user_id: #user) is registering one more nil record(n+1).
Here is the log message when I submit the contact form with only one custom record at Custom table:
Started POST "/contacts" for 127.0.0.1 at 2017-03-17 09:14:02 -0300
Processing by ContactsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nIlwxH4Ua8DjAKkMpGh8B7nxwYf6gy1Fhkdh1PaMtSANx5sB6YaOKbBUekQ4M3KP56WuHgsX31iHq2lj4+fEwA==", "contact"=>{"email"=>"test#test", "name"=>"name test", "user_id"=>"1", "contact_customs_attributes"=>{"0"=>{"value"=>"custom test"}}}, "commit"=>"Create Contact"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SQL (108.3ms) INSERT INTO "contacts" ("email", "name", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["email", "test#test"], ["name", "name test"], ["user_id", 1], ["created_at", 2017-03-17 12:14:02 UTC], ["updated_at", 2017-03-17 12:14:02 UTC]]
SQL (7.7ms) INSERT INTO "contact_customs" ("value", "contact_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["value", "custom test"], ["contact_id", 3], ["created_at", 2017-03-17 12:14:02 UTC], ["updated_at", 2017-03-17 12:14:02 UTC]]
SQL (0.6ms) INSERT INTO "contact_customs" ("contact_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["contact_id", 3], ["created_at", 2017-03-17 12:14:02 UTC], ["updated_at", 2017-03-17 12:14:02 UTC]]
(36.5ms) COMMIT
Redirected to http://localhost:3000/contacts/3
Completed 302 Found in 176ms (ActiveRecord: 154.5ms)
Try to comment or remove #contact.contact_customs.build from you create action. That is the reason you have an N+1 contact_customs with all the fields = nil.
When you do #contact = Contact.new(contact_params) you create a #contact that should look like this:
#contact = Contact.new(:email => contact_params[:email], :name => contact_params[:name], ..etc..., :custom_attributes => contact_customs_attributes: [ :id, :value, :custom_id, custom_attributes: [] ])
With that you have a #contact object instantiated and as array:
#contact.contact_customs = [ first_contact_custom => [firstvalue, secondvalue], second_contact_custom => [firstvalue, secondvalue]]
The following:
#contact.contact_customs.build
is like doing
#custom = Custom.new()
#contact.customs << #custom
Which will append that #custom entry with all fields = nil in the join table contact_customs.
#contact.contact_customs = [ first_contact_custom => [firstvalue, secondvalue], second_contact_custom => [firstvalue, secondvalue], second_contact_custom => [nil, nil] ]
So try remove the following line
#contact.contact_customs.build
The only place where you need that line is in the new action, because you need those fields instantiated for the form.
I got a model day and a model task. day has many tasks. I'm using a nested_form for this. The user enters a time and two variables, which a caculated to an index. The first task, with the highest index has a starttime= 8am.
Now I want to order the tasks by the index and add every task's time to the previous task's starttime.
My attempt to solve this:
def create
#day = current_user.days.build(day_params)
#day.save
#day.tasks.each do |task|
task.index = task.ur**2 + task.imp
end
if current_user.worktype = 1
#tasks = #day.tasks.order(index: :desc)
x = 0
#tasks.each do |task|
if x = 0
task.starttime = Time.new.beginning_of_day + 8*60*60
x = task.id
else
task.starttime = #day.task.find(x).starttime + #day.task.find(x).time*60
x = task.id
end
end
elsif current_user.worktype = 2
...
end
#day.save
respond_to do |format|
if #day.save
format.html { redirect_to #day, notice: 'Day was successfully created.' }
format.json { render :show, status: :created, location: #day }
else
format.html { render :new }
format.json { render json: #day.errors, status: :unprocessable_entity }
end
end
end
But somehow starttime remains nil, when I want to print it out in the view
- #tasks.each do |task|
...
= task.starttime.strftime("%H:%M")
I checked it in rails console too.
consolelog for POST:
Started POST "/days" for ::1 at 2016-08-04 02:19:03 +0200
Processing by DaysController#create as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"YaLq2XBUMltzCpZxvKBp5NQGUgiw/Ockto1r0zy/dZHU3HVlp4lpcsH/b3Q9WYas97ENlwRiPzCUdOiBC06GbA==", "day"=>{"tasks_attributes"=>{"1470269934695"=> {"description"=>"1", "ur"=>"1", "imp"=>"1", "time"=>"1"
, "_destroy"=>"false"}, "1470269939280"=>{"description"=>"2", "ur"=>"3", "imp"=>"3", "time"=>"2", "_destroy"=>"false"}}}, "commit"=>"Create Day"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.0ms) begin transaction
SQL (3.5ms) INSERT INTO "days" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?) [["user_id", 1], ["created_at", "2016-08-04 00:19:03.986762"], ["updated_at", "2016-08-04 00:19:03.986762"]]
SQL (0.0ms) INSERT INTO "tasks" ("description", "ur", "imp", "time", "day_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["description", "1"], ["ur", 1], ["imp", 1], ["time", 1], ["day_id", 11], ["created_at", "2016-08-04 00:19:03.992775"], ["updated_at", "2016-08-04 00:19:03.992775"]]
SQL (0.0ms) INSERT INTO "tasks" ("description", "ur", "imp", "time", "day_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["description", "2"], ["ur", 3], ["imp", 3], ["time", 2], ["day_id", 11], ["created_at", "2016-08-04 00:19:03.994776"], ["updated_at", "2016-08-04 00:19:03.994776"]]
(4.0ms) commit transaction
Task Load (0.5ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."day_id" = ? [["day_id", 11]]
Task Load (0.5ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."day_id" = ? ORDER BY "tasks"."index" DESC [["day_id", 11]]
(0.0ms) begin transaction
SQL (1.0ms) UPDATE "tasks" SET "index" = ?, "updated_at" = ? WHERE "tasks"."id" = ? [["index", 2], ["updated_at", "2016-08-04 00:19:04.006796"], ["id", 24]]
SQL (1.0ms) UPDATE "tasks" SET "index" = ?, "updated_at" = ? WHERE "tasks"."id" = ? [["index", 12], ["updated_at", "2016-08-04 00:19:04.009792"], ["id", 25]]
(3.6ms) commit transaction
(0.0ms) begin transaction
(0.0ms) commit transaction
Redirected to http://localhost:3000/days/11
Completed 302 Found in 39ms (ActiveRecord: 14.6ms)
EDIT
Building on #evanbike's answer I added a task.save everytime starttime is set. But nothing changed, so I tried and removed the If statement and now starttime is saved, but every task has the same time.
#tasks = #day.tasks.order(index: :desc)
x = 0
#tasks.each do |task|
if x = 0
task.starttime = Time.new.beginning_of_day + 8*60*60
task.save
x = task.id
else
task.starttime = #day.task.find(x).starttime + #day.task.find(x).time*60
task.save
x = task.id
end
end
#day.save
I hope someone can help me with this issue.
Thanks in advance.
When you do this, you are setting the index on the instance of the task in the #day association cache:
#day.tasks.each do |task|
task.index = task.ur**2 + task.imp
end
Then, when you do this:
#tasks = #day.tasks.order(index: :desc)
...it makes a db call (since you're calling order on it) and return new instances—that don't have index set. If you called sort or some array method, it would use the stored instances
I think the simplest would be to save the instances of tasks after you set each of the values. Calling sort on the association would probably work, but it seems brittle.
I want to upload a voice sound in my Rails project.
The recording works fine to download, but I can't send the data to rails server.
recorder && recorder.exportWAV(function (blob) {
var url = URL.createObjectURL(blob);
console.log(url);
$.ajax({
type: "POST",
url: "/voices",
data: {voice: {sound: url}}
});
});
In server log there is a post data, but sound was not created.
Started POST "/voices" for ::1 at 2015-12-08 20:43:16 +0900
Processing by VoicesController#create as */*
Parameters: {"voice"=>{"sound"=>"blob:http%3A//localhost%3A3000/3ad3859e-b960-44b8-ba18-20727e739bab"}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Profile Load (0.3ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT 1 [["user_id", 1]]
(0.2ms) BEGIN
SQL (0.5ms) INSERT INTO "voices" ("sound", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["sound", nil], ["created_at", "2015-12-08 11:43:16.254713"], ["updated_at", "2015-12-08 11:43:16.254713"]]
(0.6ms) COMMIT
Completed 500 Internal Server Error in 135ms (ActiveRecord: 3.4ms)
How can I pass the sound blob data to rails server?
voices_controller.rb
class VoicesController < ApplicationController
#voice = Voice.new(voice_params)
respond_to do |format|
if #voice.save
format.html { redirect_to root_path, notice: 'voice was successfully created.' }
format.json { render :show, status: :created, location: root_path }
else
format.html { render :new }
format.json { render json: #voice.errors, status: :unprocessable_entity }
end
end
def voice_params
params.require(:voice).permit(:sound, :user_id)
end
end
app/models/voice.rb
class Voice < ActiveRecord::Base
belongs_to :phrase
belongs_to :user
mount_uploader :sound, SoundUploader
end
Another attempt
recorder && recorder.exportWAV(function (blob) {
var url = URL.createObjectURL(blob);
console.log(url);
var formData = new FormData();
formData.append('voice[sound]', url);
$.ajax({
type: "POST",
url: "/voices",
data: formData
});
});
This codes ends up with a error Uncaught TYpeError: Illegal invocation.
Not sure, if you are trying to post the data correctly or have your models setup properly. you need to save your audio as a file, using File.open(filename, w)
SQL (0.5ms) INSERT INTO "voices" ("sound", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["sound", nil], ["created_at", "2015-12-08 11:43:16.254713"], ["updated_at", "2015-12-08 11:43:16.254713"]]
The SQL, is suggesting, that nothing is getting passed to "sound" field.
if you are passing it as a blob, you need to set the column accordingly, if not done entirely, however better option would be 2)
Send and save the audio data as a file. Have a look at link
formData.append('voice[sound]', url); # Comment this
formData.append('voice[sound]', blob); # This will send the actual data to your server and not the blob url. then your carrierwave will have the file data, which it can save.
The user can choose of one of two submit buttons. If he clicks <%= f.submit :conceal %> how can the default value be made to change from false to true?
t.boolean "conceal", default: false
because right now if the user clicks the button - the default value remains false:
[1] pry(main)> Valuation.find(9)
Valuation Load (0.2ms) SELECT "valuations".* FROM "valuations" WHERE "valuations"."id" = ? LIMIT 1 [["id", 9]]
=> #<Valuation:0x007fdf26c736b8
id: 9,
conceal: false,
user_id: 1,
created_at: Thu, 23 Apr 2015 16:21:31 UTC +00:00,
updated_at: Thu, 23 Apr 2015 16:21:31 UTC +00:00,
likes: nil,
name: "Conceal/Private/Hide">
This didn't work <%= f.submit :conceal => true %>.
class ValuationsController < ApplicationController
before_action :set_valuation, only: [:show, :edit, :update, :destroy, :like]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
#valuations = Valuation.tagged_with(params[:tag])
else
#valuations = Valuation.order('RANDOM()')
end
end
def show
#valuation = Valuation.find(params[:id])
#commentable = #valuation
#comments = #commentable.comments
#comment = Comment.new
end
def new
#valuation = current_user.valuations.build
end
def edit
end
def create
#valuation = current_user.valuations.build(valuation_params)
if #valuation.save
track_activity #valuation
redirect_to #valuation, notice: 'Value was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
def update
if #valuation.update(valuation_params)
track_activity #valuation
redirect_to #valuation, notice: 'Value was successfully updated'
else
render action: 'edit'
end
end
def destroy
#valuation.destroy
redirect_to valuations_url
end
def like
without_tracking do
#valuation.increment!(:likes)
end
#valuation.create_activity :like
flash[:success] = 'Thanks for sharing your Value!'
redirect_to valuation_path(#valuation)
end
private
def without_tracking
Valuation.public_activity_off
yield if block_given?
Valuation.public_activity_on
end
def set_valuation
#valuation = Valuation.find(params[:id])
end
def correct_user
#valuation = current_user.valuations.find_by(id: params[:id])
redirect_to valuations_path, notice: "Not authorized to edit this valuation" if #valuation.nil?
end
def valuation_params
params.require(:valuation).permit(:name, :conceal, :tag_list, :content, :commentable, :comment, :like)
end
end
UPDATE
Started POST "/valuations" for 127.0.0.1 at 2015-04-23 15:27:35 -0400
Processing by ValuationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xd4ISNLZxjryLJfxvauWUANBzJthCNBzUwhtxseB/ird77mdYoKY/f9Skzb68lClaWOIUJXie9qC0jI1l+d98w==", "valuation"=>{"name"=>"PRIVATE AGAIN", "tag_list"=>""}, "commit"=>"conceal"}
[1m[36mUser Load (0.7ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1[0m [["id", 1]]
[1m[35mHabit Load (0.2ms)[0m SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ? [["user_id", 1]]
[1m[36mHabit Load (0.2ms)[0m [1mSELECT "habits".* FROM "habits"[0m
[1m[35mActsAsTaggableOn::Tag Load (0.2ms)[0m SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35mSQL (31.7ms)[0m INSERT INTO "valuations" ("name", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "PRIVATE AGAIN"], ["user_id", 1], ["created_at", "2015-04-23 19:27:36.015267"], ["updated_at", "2015-04-23 19:27:36.015267"]]
[1m[36mActsAsTaggableOn::Tag Load (0.1ms)[0m [1mSELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)[0m [["taggable_id", 15], ["taggable_type", "Valuation"]]
[1m[35m (10.8ms)[0m commit transaction
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35mSQL (1.7ms)[0m INSERT INTO "activities" ("action", "trackable_id", "trackable_type", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["action", "create"], ["trackable_id", 15], ["trackable_type", "Valuation"], ["user_id", 1], ["created_at", "2015-04-23 19:27:36.136688"], ["updated_at", "2015-04-23 19:27:36.136688"]]
[1m[36m (1.5ms)[0m [1mcommit transaction[0m
Redirected to http://0.0.0.0:3000/valuations/15
The submit method takes an argument for what name it will show up as, but that's only useful for determining which button, if there's more than one, was used to submit the form.
What you want to do is introduce a hidden field that has the right naming convention so you can use update_attributes, or you need to test for the presence of params[:commit] which, if present, means someone pressed that button:
if (params[:commit] == 'conceal')
#valuation.conceal = true
end
In javascript I do an ajax call to the create function of deliveries_controller. This puts a new Delivery in the database with a product and quantity. I also try to put the current_user as user_id in the database, but for some reason it stays nil in the database.
My ajax call:
$.ajax({
type: "POST",
url: "/deliveries",
data: { delivery: {ingredient: "meel", quantity: "800", scenario_id: "3"} },
success: function(){
alert('Success!');
},
error: function(){
alert('No success');
}
});
I just pass some dummy data to test it all out.
and my deliveries_controller:
class DeliveriesController < ApplicationController
protect_from_forgery
def index
#storages = Storage.where(user_id: current_user)
end
def addQuantity
#storage = Storage.where(user_id: current_user.id)
#storage.update_all ("quantity = (quantity+200)")
redirect_to deliveries_url
end
def create
#delivery = Delivery.new(delivery_params)
respond_to do |format|
if #delivery.save
format.html do
render :nothing => true
end
format.json { render json: #delivery.to_json }
else
format.html { render :nothing => true} ## Specify the format in which you are rendering "new" page
format.json { render json: #delivery.errors } ## You might want to specify a json format as well
end
end
end
private
def delivery_params
params.require(:delivery).permit(:user_id, :ingredient, :quantity, :scenario_id)
end
end
New entries are created in the database, but whichever way I try to pass the user_id as param it isn't saved in the database.
I tried it like:
#delivery = Delivery.new(delivery_params, :user_id => current_user),
#user_id = current_user
#delivery = Delivery.new(delivery_params, #user_id)
and
params.require(:delivery).permit(:user_id, :ingredient, :quantity, :scenario_id).merge(user_id: current_user)
log:
Started POST "/deliveries" for 127.0.0.1 at 2014-11-03 12:59:37 +0100
Processing by DeliveriesController#create as */*
Parameters: {"delivery"=>{"ingredient"=>"meel", "quantity"=>"800", "scenario_id"=>"3"}}
Can't verify CSRF token authenticity
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' LIMIT 1
(0.0ms) begin transaction
SQL (0.2ms) INSERT INTO "deliveries" ("created_at", "ingredient", "quantity", "scenario_id", "updated_at") VALUES (?, ?, ?, ?, ?) [["created_at", "2014-11-03 11:59:37.253274"], ["ingredient", "meel"], ["quantity", 800], ["scenario_id", 3], ["updated_at", "2014-11-03 11:59:37.253274"]]
(12.5ms) commit transaction
Rendered text template (0.0ms)
Completed 200 OK in 24ms (Views: 0.8ms | ActiveRecord: 13.1ms)
but the user_id for Delivery stays nil. How would I pass the user_id from the current_user so it's saved in the database with the json I retrieve from the ajax call?
Thanks in advance
EDIT:
I fixed it the following way:
I send json data to javascript with content_tag:
= content_tag(:div,"", id: "storages", data:{url: Storage.where(user_id: current_user)})
this data is handled, and the user_id is suddenly accepted :)
thanks for the help!
Try this instead
#delivery = current_user.deliveries.new(delivery_params)
It should be
#delivery = Delivery.new(delivery_params.merge(user: current_user))
OR
#delivery = Delivery.new(delivery_params)
#delivery.user = current_user
Put current user_id on hidden field on HTML and send it with ajax like other params