无法将post保存到数据库。

时间:2021-08-09 12:09:20

I have an Event app, where I am using a calendar. I have created 2 external routes and controller action to #save and #load data and I have 2 templates for them. One is save.json.erb other one is load.json.erb. For now, I have hardcoded the load data from load.json.erb, looks like;

我有一个事件应用程序,我使用日历。我已经为#save和#load数据创建了两个外部路由和控制器操作,我有两个模板。一个是save.json。另一个是load.json.erb。现在,我已经硬编码了load.json的加载数据。erb的样子;

{"2015-05-06": {"available":"1",
                           "bind":0,
                           "info":"",
                           "notes":"",
                           "price":"20",
                           "promo":"",
                           "status":"available"
  },

"2015-05-07": {"available":"1",
                           "bind":0,
                           "info":"",
                           "notes":"",
                           "price":"20",
                           "promo":"",
                           "status":"available"
  }}

So, it shows the hardcoded data on the calendar.

因此,它显示了日历上的硬编码数据。

My problem is, when I press submit, it does not give an error but it does not save it to database. I could not figure out the strong params either. I am using permit! for now to see it saves to database. Maybe my Event Model and its columns are wrong. Because I could not figure it out what it posts (integer, string etc..)

我的问题是,当我按下submit时,它不会出错,但它不会将它保存到数据库中。我也弄不清那些强壮的帕姆斯。我使用许可证!目前来看,它节省了数据库。也许我的事件模型和它的列是错误的。因为我无法计算出它的位置(整数,字符串等等)

Here is my events_controller

这是我events_controller

....
def load

  end

  def save
    #THIS IS WRONG I SHOULD PUT SMTH ELSE
    @event = Event.new
    @event.save

  end

 def event_params
      params.require(:event).permit!
    end

when I select data from calendar press submit it sends this;

当我从日历新闻中选择数据时,提交它;

HEADER:
    event_id:0
    event:{"2015-05-06":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-07":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-27":{"available":"1","bind":0,"info":"demo","notes":"demodemodemo","price":"15","promo":"2","status":"available"}}

Also from the log; Is this data JSON?, or I have to use JSON.parse somewhere?

也从日志;这是JSON数据吗?或者我必须使用JSON。解析的地方吗?

Started POST "/events/save" for ::1 at 2015-05-02 18:39:42 +0300
Processing by EventsController#save as */* #HERE IT SENDS THE PARAMETERS, BUT I COULD NOT GET THEM
  Parameters: {"event_id"=>"0", "event"=>"{\"2015-05-06\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"20\",\"promo\":\"\",\"status\":\"available\"},\"2015-05-07\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"20\",\"promo\":\"\",\"status\":\"available\"},\"2015-05-27\":{\"available\":\"1\",\"bind\":0,\"info\":\"demo\",\"notes\":\"demodemodemo\",\"price\":\"15\",\"promo\":\"2\",\"status\":\"available\"}}"}
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "events" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2015-05-02 15:39:42.823906"], ["updated_at", "2015-05-02 15:39:42.823906"]]
   (2.4ms)  commit transaction
  Rendered events/save.json.erb (0.1ms)
Completed 200 OK in 21ms (Views: 12.9ms | ActiveRecord: 3.0ms)

When I try;

当我尝试;

def save

    @event = Event.new(event_params)
    @event.save

  end

def event_params
      params.require(:event).permit!
    end

It gives an error of ;

它给出了一个错误;

NoMethodError in EventsController#save

undefined method `permit!' for #<String:0x007fcbb99d24c0>

So I think it is posted as a string instead of a hash.

所以我认为它是作为字符串而不是散列来发布的。

For me, there is something wrong with the data it sends to database or the database can not configured for these datas. Because of #save action has @events = Event.new all the time it creates new event in the database and saves it.So I have to get the POSTed data but I could not get those parameters. I think I have to take the POSTed data and with for loops I have to take those data and save it to database. Could not find a way. Hope someone helps

对我来说,它发送到数据库的数据或数据库无法为这些数据配置的数据有问题。因为#save操作有@events =事件。它会在数据库中创建新的事件并保存它。所以我必须得到发布的数据但我不能得到这些参数。我想我必须把发布的数据和循环,我必须把这些数据保存到数据库。我找不到路。希望有人帮助

Here is the full HEADER:

这是完整的标题:

Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:0
Content-Type:application/json; charset=utf-8
Date:Sat, 02 May 2015 18:42:54 GMT
Server:WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)
Set-Cookie:_demo_session=Snh1Nm5CNWJzTHNITXp5SkRDejNmZzRXRkdoVm5SeEkwUW82WmE5QkFndThkeUdyTEdBK2s3ZVR1aEUxQXpGclpqR202WTIzSGkzNWtIQUdWZXFFeUtmSVpBbnZZNmJnN090YUxXS2c5eFFPVzZOaXJjTGJndGRsS0xBcUhaU0VlMFAvRVdtT05RMHpLcUYrSy9wSElnPT0tLUI2SWFiOHZXRlpqMmpteVloV3Zsb2c9PQ%3D%3D--3533fcf1e966b5c1e766dcc099caa6df4b5c284f; path=/; HttpOnly
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:7863cf16-0162-4760-8719-d155202eca7a
X-Runtime:0.030455
X-Xss-Protection:1; mode=block
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:3126
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:_Paint_session=NXN5NVUvemhXcHF2UnF1ZlBXTHhtZVVWODlyVWFoL0tEWU9vWCtOYVp6ck9EUVF6OUs0WTJYV21yWW5VeVhqdndST2JUYTdCdnNnamNzZDJjQXFLNE1CYzlQT3dtcVJiRTJLcmlwaXR3aFdKZUZBVXN4VitWamMzaWdZUUtTQU1mcWhIRFg3SnJwQ2FBK1hmclZ3WmtiODRuTUpVRUVLKzYzQTNuUGxCTURYMHhKN3Z6eUZtbURLS2MybVlNejNoTmo5MVZteUQzcG8wTnB6WUFlR2pRK2UwSHFnUTVua0hUM0VzWitLUTdya1BXVVZ1eTVKUmNCR3pQaEh2djlpcFo3dFU1WmhZYlhSWS9wYTBVSHRTYXc9PS0tbDJHT3A3NVJ1Tm5OczVIREM2emNLQT09--f2703914b69129404c69d1d9dbb446fde16c6442; _Resim_session=cXQ5cEE5ZjFPNU1Jby9ZY0lKWis2TVY1NVlaN2dVZGtSaDdzc3B1QU9saS9yNXNU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VkQlh2bERBRUM4c0NVNnFsTFdmbVB1cURJeDVHUkhKOWZUOG5pUlhFZkxOSkJ3c01uU2paTW50WXRrRW8zRmJtTTBrUm5GWlJvbz0tLUh4ckZqdnA3WGQzRjdmNnAzMXdMcmc9PQ%3D%3D--622d3f9adb9afb871e118d0715921aaf986f82d2; _Cal_session=cjRlSlc0Q2FITHJJTmlTbU5TZjk5aFNFaTczTHRQZW9TR0h1MG4xYVovZG9xaUxyNittWENjbXdib3FLc1J6cXh3dHA5YitaVkZYbFVtaFI2bGxUKzJyM1kvRzJlRFV4b0JibzJ1TTdQS0ZkdVE2eVJJSlZQVXY0Q0thS1NBRzhGUzlaQ1ZRaHppYzJES2V2eXRmVWtBPT0tLWEzVWFIcWl0WnJBRVdnanJ0em1Renc9PQ%3D%3D--03a65bd6c5338108d2d3db62295843f8b3e3eaaa; _fullcalendar_and_rails_example_session=M1h0eFJieVY1ek16OWRtR1JRUGc1eCtsdFZnTDdqWkd3NndWQTFuUzFKdHJpOHlRYSsweHZ6UGZubTV1eEdJZm14NVZxbE1IUHZzRG1id2NVeENERzFlaFF3NzFNWHk0RlltbS8yNmc2aEtnYjJDcGZmY3pZWG0vU0RsU29ST005NDVpdVpYSWtNTURkM3M2RmVvZU8vUStwdUxFNk1TaVJTRDY1Z2FKcEd4QkxZMlpGeUlsUGl5UlNCVWhPNk5qR082T25lZlZ4NkIxY012MjRJaVVTKzFqdUZFMUVjc1VxVnA0UXFwSVFEbW1acE9KMWw1N0xzQWJlYUd6R200Q1VCdkJjUWpTbElrbFhlZ2ZBdnY2WnB1NHdHU2tBQTlQandzekR5SmJkbnVhU08vNWpLNjFuY1UyVUxuZWt2ZWotLTY3TU9jZklCcVR6ZXZQRy9UUCtHTmc9PQ%3D%3D--9bcb70f5196a063e7915b11622953f7935d9166c; _takvim_session=WVJmQVpEbEJUOE9KeVdLK3ZyODRpejI0dzA2aWJPd2dqOGRCaysxOU5VT3lhVkNnNzNIZytvYlpqL2FRZGhTWXZFcWxLc3JYVmoyUVRibGFuelpCczl4eFVjaFVLdkZiRURpUC84cysyUldFbC9VT295SURnMkpDQnFtdldLdUhHeDhRL3NGOG90WS9mWUI1WitocndBPT0tLVp6Mk1VS2VaT0hmMGtwcnhNcnpYMkE9PQ%3D%3D--a215e9c8f635c5c638ccdcd55105c3bdc452760e; SQLiteManager_currentLangue=2; request_method=GET; _Last_session=VnErWEFwazE3dWFBdm94WUVhMXdYWFhKVnViUmtQWUFja0xENjNDTmYxWVAxbjVyVDZrK3pxRlVjUnp0MGQ3R240UWZSK2lNcld5bDVKM2ZYb3JwMTJ1QXpPa0p1cFJOYXFXUllIakVrdnBzVHh2V09YQlZGTHNjTWtNLzFDOXNTdUhYZGNXei80enRwclZkdzBCUzZFcUtEQVFqeDFock15anMrVnVIUHRRPS0tci9lSEMvNFBtVWJ5eW1BSTQ0VUpadz09--46ddca06b8e604506dcfff84e7cc8111c7a1b679; _demo_session=TzE2bi93R2E3ZXVNSHdkZ0MvVnRCTm5BeG1VQ0luMVQrWFJ5a1FhbTc4amNCSGFNazJYTVhVYlRxbEhGejlnREowTTJDVFByYkoveHRpeEx6SlZvRnpaQ3R3UEdWaVRlK25UK29SQmx5Nmplbk9Gb1NNZ0pYdm9PQ3FLeTFKZ25CdkF4USt0clpGN1dMUkxrekxTM3lRPT0tLTZoQ1F4UHg3VExsa3JaMWRxQ1IvTFE9PQ%3D%3D--a430ecd15a69103694b06ec430875e21b66f5e62
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/events
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
X-CSRF-Token:GT/gFRykJMorJu4yPLmLwwGz1EZIwlVSp8XWeO1SOvIVYITeJLAPa1YcYkJOswrkXqMUUFb/jk/DP8JtvLhQYQ==
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
event_id:0
event:{"2015-05-06":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-07":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-13":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-14":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-15":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-16":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-17":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-20":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-21":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-22":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-23":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-24":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-28":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-29":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-30":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-31":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"}}

and Here is my database schema;

这是我的数据库模式;

ActiveRecord::Schema.define(version: 20150502145455) do

  create_table "events", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "start_time"
    t.datetime "end_time"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.string   "status"
    t.float    "price"
    t.float    "promo"
    t.integer  "available"
    t.text     "info"
    t.text     "notes"
    t.boolean  "bind"
    t.string   "time"
    t.string   "p"
    t.string   "event_id"
  end

end

EDIT 1: Here is the Jquery request;

编辑1:这是Jquery请求;

<script>
$(document).ready(function() {
    $('#backend').DOPBackendBookingCalendarPRO({

        'DataURL': '/events/load', #TO LOAD DATA
        'SaveURL': '/events/save'  #TO SAVE DATA
    });
});
</script>

I have shared load.js.erb file as it is harcoded right now. But save.js.erb file is empty. When I created the url, rails asked me to define template. But #create action does not have a template,right?. This calendar was written for php but I am trying to use it on RoR. The guy who wrote it, I do not know why, they defined 2 post urls one to retrieve data one to send data. Normally, one of them should be get, right?. That is why I created 2 post urls in routes.rb.Anyway. If you can help, I can send the calendar project I do not know how, but you see their backend.js file. Maybe I should change something there. Thank you

我有load.js共享。erb文件,因为它现在被编码。但save.js。erb文件是空的。当我创建url时,rails要求我定义模板。但是#create操作没有模板,对吧?这个日历是为php编写的,但我正在尝试在RoR上使用它。写它的人,我不知道为什么,他们定义了两个post url一个用来检索数据一个发送数据。正常情况下,其中一个应该得到,对吧?这就是为什么我在路由中创建了两个post url。如果你能帮忙,我可以发送我不知道的日历项目,但是你看到他们的后端。js文件。也许我应该改变一下。谢谢你!

Here at the top of the backend.js file, I have ;

在后台的顶部。js文件,我有;

 Schedule = {},

And there is this function in backend..js file to load data

在后端有这个函数。js文件加载数据。

                 parseCalendarData:function(){
                        $.post(DataURL, {event_id:ID}, function(data){
                            console.log(typeof data); //THIS RETURNS OBJECT
                            if(typeof data === 'object') {
                        Schedule = data; 
                        }
                        else {
                            data = $.trim(data).replace(/\\/gi, '');

                        if (data != ''){
                                Schedule = JSON.parse(data);
                            }
                        }
                            methods.initCalendar();
                        });
                    },

Before save data, here is the code to set submitted data, probably the problem is there;

在保存数据之前,这里是设置提交数据的代码,可能存在问题;

setData:function(){// Set submited data.
                        var y, m, d, noDays, key,
                        startDate, sYear, sMonth, sDay,
                        endDate, eYear, eMonth, eDay,
                        fromMonth, toMonth, fromDay, toDay,
                        availableValue = $('#DOPBCP_available').val(),
                        bindValue = 0,
                        infoValue = $('#DOPBCP_info').val().replace(/\n/gi, '<br />'),
                        notesValue = $('#DOPBCP_notes').val().replace(/\n/gi, '<br />'),
                        priceValue = $('#DOPBCP_price').val() != undefined ? $('#DOPBCP_price').val():'',
                        promoValue = $('#DOPBCP_promo').val() != undefined ? $('#DOPBCP_promo').val():'',
                        statusValue = $('#DOPBCP_status').val();

                        startDate = dayStartSelection < dayEndSelection ? dayStartSelection.split('_')[1]:dayEndSelection.split('_')[1];
                        endDate = dayStartSelection < dayEndSelection ? dayEndSelection.split('_')[1]:dayStartSelection.split('_')[1];

                        sYear = parseInt(startDate.split('-')[0], 10);
                        sMonth = parseInt(startDate.split('-')[1], 10);
                        sDay = parseInt(startDate.split('-')[2], 10);

                        eYear = parseInt(endDate.split('-')[0], 10);
                        eMonth = parseInt(endDate.split('-')[1], 10);
                        eDay = parseInt(endDate.split('-')[2], 10);

                        if (Schedule[methods.previousDay(startDate)] != undefined){
                            if (Schedule[methods.previousDay(startDate)]['bind'] == 1){
                                Schedule[methods.previousDay(startDate)]['bind'] = 0;
                            }
                            else if (Schedule[methods.previousDay(startDate)]['bind'] == 2){
                                Schedule[methods.previousDay(startDate)]['bind'] = 3;
                            }
                        }

                        if (Schedule[methods.nextDay(endDate)] != undefined){
                            if (Schedule[methods.nextDay(endDate)]['bind'] == 2){
                                Schedule[methods.nextDay(endDate)]['bind'] = 1;
                            }
                            else if (Schedule[methods.nextDay(endDate)]['bind'] == 3){
                                Schedule[methods.nextDay(endDate)]['bind'] = 0;
                            }
                        }

                        for (y=sYear; y<=eYear; y++){
                            fromMonth = 1;

                            if (y == sYear){
                                fromMonth = sMonth;
                            }

                            toMonth = 12;

                            if (y == eYear){
                                toMonth = eMonth;
                            }

                            for (m=fromMonth; m<=toMonth; m++){
                                noDays = new Date(y, m, 0).getDate();
                                fromDay = 1;

                                if (y == sYear && m == sMonth){
                                    fromDay = sDay;
                                }

                                toDay = noDays;

                                if (y == eYear && m == eMonth){
                                    toDay = eDay;
                                }

                                for (d=fromDay; d<=toDay; d++){
                                    key = y+'-'+prototypes.timeLongItem(m)+'-'+prototypes.timeLongItem(d);

                                    if ($('#DOPBCP_group').is(':checked')){
                                        if (key == startDate){
                                            bindValue = 1;
                                        }
                                        else if (key == endDate){
                                            bindValue = 3;
                                        }
                                        else{
                                            bindValue = 2;
                                        }
                                    }
                                      //HERE IS THE PROBLEM I GUESS
                                    Schedule[key] = {"available": availableValue,
                                                     "bind": bindValue,
                                                     "info": infoValue,
                                                     "notes": notesValue,
                                                     "price": priceValue,
                                                     "promo": promoValue,
                                                     "status": statusValue};
                                }
                            }
                        }
                        methods.saveData();
                    },

Lastly the save function in js file;

最后是js文件中的save函数;

                   saveData:function(){// Save data.
                        var today = new Date(),
                        dd = prototypes.timeLongItem(today.getDate()),
                        mm = prototypes.timeLongItem(today.getMonth()+1),
                        yyyy = today.getFullYear();

                        for (var day in Schedule){
                            if (day < yyyy+'-'+mm+'-'+dd){
                                delete Schedule[day];
                            }
                        }

                        methods.hideForm();
                        methods.generateCalendar(StartYear, dayStartSelectionCurrMonth);

                        $.post(SaveURL, {event_id:ID, event:JSON.stringify(Schedule)}, function(data){});
                    },

PS: I have tried this in the events controller;

PS:我已经在事件控制器中尝试过了;

def save
    respond_to do |format|
      @event = Event.new(event_params)
      @event.save

      format.html
      format.json { render :json => @event, :content_type => 'application/json'  }
    end
  end

But content type did not change.

但内容类型没有改变。

EDIT 2:

编辑2:

Sorry for giving you so much trouble but I am really trying to learn. I have changed $.post to $.ajaxand I changed the controller as you suggested. Now it try to post array and I am planing to iterate over the hash to get datas and save it. As you said I can then loop over params[:event] as it contains all the data, right?.Because of the multiple data it gives an nil error, that is why I would like to loop over them(I changed the #create as you said);

很抱歉给你添了这么多麻烦,但我真的在努力学习。我改变了美元。美元。ajaxand我按照你的建议修改了控制器。现在它尝试post数组,我打算遍历散列以获取数据并保存它。正如您说的那样,我可以遍历params[:事件],因为它包含了所有的数据,对吗?因为有多个数据,它会给出一个nil的错误,这就是为什么我想对它们进行循环(我改变了#create就像您说的那样);

NoMethodError in EventsController#create

undefined method `new' for nil:NilClass

I think this is because Schedule; (key is the selected date)

我认为这是因为日程安排;(关键是选定日期)

Schedule[key]  =    {"date": key,
                     "available": availableValue,
                     "bind": bindValue,
                     "info": infoValue,
                     "notes": notesValue,
                     "price": priceValue,
                     "promo": promoValue,
                     "status": statusValue};
}

This is what comes from the Network tab;

这是来自网络标签的东西;

Connection:Keep-Alive
Content-Length:94953
Content-Type:text/plain; charset=utf-8
Date:Sun, 03 May 2015 15:26:09 GMT
Server:WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)
X-Request-Id:1d59e6cd-726f-4eb0-afdf-92205c8a0974
X-Runtime:0.390420
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:1687
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:_Paint_session=NXN5NVUvemhXcHF2UnF1ZlBXTHhtZVVWODlyVWFoL0tEWU9vWCtOYVp6ck9EUVF6OUs0WTJYV21yWW5VeVhqdndST2JUYTdCdnNnamNzZDJjQXFLNE1CYzlQT3dtcVJiRTJLcmlwaXR3aFdKZUZBVXN4VitWamMzaWdZUUtTQU1mcWhIRFg3SnJwQ2FBK1hmclZ3WmtiODRuTUpVRUVLKzYzQTNuUGxCTURYMHhKN3Z6eUZtbURLS2MybVlNejNoTmo5MVZteUQzcG8wTnB6WUFlR2pRK2UwSHFnUTVua0hUM0VzWitLUTdya1BXVVZ1eTVKUmNCR3pQaEh2djlpcFo3dFU1WmhZYlhSWS9wYTBVSHRTYXc9PS0tbDJHT3A3NVJ1Tm5OczVIREM2emNLQT09--f2703914b69129404c69d1d9dbb446fde16c6442; _Resim_session=cXQ5cEE5ZjFPNU1Jby9ZY0lKWis2TVY1NVlaN2dVZGtSaDdzc3B1QU9saS9yNXNUUHE5N2d1Ym1CZjcxYlNNZjAwbnhPNm9oeEN0aUpNUXZYMXM1Q2ZHWHJuZ3lhdjhxRmxteVR3ZXFvNHdxMFJZcXp6NWZMbk1qWVJyZG5GVFdB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QzRjdmNnAzMXdMcmc9PQ%3D%3D--622d3f9adb9afb871e118d0715921aaf986f82d2; _Cal_session=cjRlSlc0Q2FITHJJTmlTbU5TZjk5aFNFaTczTHRQZW9TR0h1MG4xYVovZG9xaUxyNittWENjbXdib3FLc1J6cXh3dHA5YitaVkZYbFVtaFI2bGxUKzJyM1kvRzJlRFV4b0JibzJ1TTdQS0ZkdVE2eVJJSlZQVXY0Q0thS1NBRzhGUzlaQ1ZRaHppYzJES2V2eXRmVWtBPT0tLWEzVWFIcWl0WnJBRVdnanJ0em1Renc9PQ%3D%3D--03a65bd6c5338108d2d3db62295843f8b3e3eaaa; _fullcalendar_and_rails_example_session=M1h0eFJieVY1ek16OWRtR1JRUGc1eCtsdFZnTDdqWkd3NndWQTFuUzFKdHJpOHlRYSsweHZ6UGZubTV1eEdJZm14NVZxbE1IUHZzRG1id2NVeENERzFlaFF3NzFNWHk0RlltbS8yNmc2aEtnYjJDcGZmY3pZWG0vU0RsU29ST005NDVpdVpYSWtNTURkM3M2RmVvZU8vUStwdUxFNk1TaVJTRDY1Z2FKcEd4QkxZMlpGeUlsUGl5UlNCVWhPNk5qR082T25lZlZ4NkIxY012MjRJaVVTKzFqdUZFMUVjc1VxVnA0UXFwSVFEbW1acE9KMWw1N0xzQWJlYUd6R200Q1VCdkJjUWpTbElrbFhlZ2ZBdnY2WnB1NHdHU2tBQTlQandzekR5SmJkbnVhU08vNWpLNjFuY1UyVUxuZWt2ZWotLTY3TU9jZklCcVR6ZXZQRy9UUCtHTmc9PQ%3D%3D--9bcb70f5196a063e7915b11622953f7935d9166c; _takvim_session=WVJmQVpEbEJUOE9KeVdLK3ZyODRpejI0dzA2aWJPd2dqOGRCaysxOU5VT3lhVkNnNzNIZytvYlpqL2FRZGhTWXZFcWxLc3JYVmoyUVRibGFuelpCczl4eFVjaFVLdkZiRURpUC84cysyUldFbC9VT295SURnMkpDQnFtdldLdUhHeDhRL3NGOG90WS9mWUI1WitocndBPT0tLVp6Mk1VS2VaT0hmMGtwcnhNcnpYMkE9PQ%3D%3D--a215e9c8f635c5c638ccdcd55105c3bdc452760e; SQLiteManager_currentLangue=2; request_method=GET; _Last_session=VnErWEFwazE3dWFBdm94WUVhMXdYWFhKVnViUmtQWUFja0xENjNDTmYxWVAxbjVyVDZrK3pxRlVjUnp0MGQ3R240UWZSK2lNcld5bDVKM2ZYb3JwMTJ1QXpPa0p1cFJOYXFXUllIakVrdnBzVHh2V09YQlZGTHNjTWtNLzFDOXNTdUhYZGNXei80enRwclZkdzBCUzZFcUtEQVFqeDFock15anMrVnVIUHRRPS0tci9lSEMvNFBtVWJ5eW1BSTQ0VUpadz09--46ddca06b8e604506dcfff84e7cc8111c7a1b679; _demo_session=R1dIMnpjMU1BTkszczFzZTR2Zmk3cFMyUVU2Yk12eEwyZ2poR2RWUzhQWEtPbEM5UkMrQXRJb21oc1grWkFNNlpVM2VwMElvMnI1YUN2UlFVeXR2KytqYzJyN3AxeS9lM3gxVlNhLysxQzNLMklQOGszdUZBaEREMGQwZVMzc09BNFVndjRZaGQzY25KZGwrR0wyME5nPT0tLUEreS9acGZTWUhzdXdOc0hrVW5WYVE9PQ%3D%3D--9a636d832705858099e968c44c959b12980b6e99
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/events
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
X-CSRF-Token:BaHKI75O/nhl2kbiQDxSvJeZHiUAlTttTPGd0b/usf4J/q7ohlrV2RjgypIyNtObyIneMx6o4HAoC4nE7gTbbQ==
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
event[2015-05-06][available]:1
event[2015-05-06][bind]:0
event[2015-05-06][info]:
event[2015-05-06][notes]:
event[2015-05-06][price]:20
event[2015-05-06][promo]:
event[2015-05-06][status]:available
event[2015-05-07][available]:1
event[2015-05-07][bind]:0
event[2015-05-07][info]:
event[2015-05-07][notes]:
event[2015-05-07][price]:20
event[2015-05-07][promo]:
event[2015-05-07][status]:available
event[2015-05-20][date]:2015-05-20
event[2015-05-20][available]:1
event[2015-05-20][bind]:0
event[2015-05-20][info]:
event[2015-05-20][notes]:
event[2015-05-20][price]:
event[2015-05-20][promo]:
event[2015-05-20][status]:available
event[2015-05-21][date]:2015-05-21
event[2015-05-21][available]:1
event[2015-05-21][bind]:0
event[2015-05-21][info]:
event[2015-05-21][notes]:
event[2015-05-21][price]:
event[2015-05-21][promo]:
event[2015-05-21][status]:available
event[2015-05-22][date]:2015-05-22
event[2015-05-22][available]:1
event[2015-05-22][bind]:0
event[2015-05-22][info]:
event[2015-05-22][notes]:
event[2015-05-22][price]:
event[2015-05-22][promo]:
event[2015-05-22][status]:available
event[2015-05-23][date]:2015-05-23
event[2015-05-23][available]:1
event[2015-05-23][bind]:0
event[2015-05-23][info]:
event[2015-05-23][notes]:
event[2015-05-23][price]:
event[2015-05-23][promo]:
event[2015-05-23][status]:available

EDIT 3:

编辑3:

h = {"event"=>{"2015-05-06"=>{"available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"20", "promo"=>"", "status"=>"available"}, "2015-05-07"=>{"available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"20", "promo"=>"", "status"=>"available"}, "2015-05-18"=>{"date"=>"2015-05-18", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-19"=>{"date"=>"2015-05-19", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-20"=>{"date"=>"2015-05-20", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-21"=>{"date"=>"2015-05-21", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-22"=>{"date"=>"2015-05-22", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-23"=>{"date"=>"2015-05-23", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}}}


h.each do |key, value|
  puts key
  value.each do |key2, value2|
    puts key2
    value2.each do |k, v|
    puts k
    puts v
    end
  end
end

Something like the code works fine to get the key and values, however I do not know if that works if I put it to controller.Then I should save it to database. I surely think there must be a easier way. But I am dependent on the calendar js code that the person wrote. Sorry again asking too much. If you can guide me I appreciate. Thank you again

类似于代码的代码可以很好地获取键值和值,但是我不知道如果我把它放到控制器中,它是否有效。然后我应该把它保存到数据库。我认为肯定有更简单的方法。但是我依赖于这个人写的日历js代码。再次抱歉,问得太多了。如果你能引导我,我很感激。再一次感谢您

In my controller #create action I am able to iterate over key and values; Now I have to figure out how to save them

在我的控制器#create action中,我可以遍历键和值;现在我得想办法救他们了。

def create
 h = params[:event] 
    h.each do |key, value|
      puts key
      value.each do |key2, value2|
        puts key2
        puts value2
      end
    end
end

1 个解决方案

#1


0  

You haven't detailed how you are actually sending the JSON request but two things are going wrong:

您还没有详细说明如何发送JSON请求,但有两件事情正在出错:

Your save action expects a hash with the key event with:

您的save操作预期与关键事件的散列:

{
  event: {
    title: "foo"
    # more attributes ...
  }
}

But you're trying to send the parameters for several dates at the same time.

但是,您尝试同时发送多个日期的参数。

event:{ 
 "2015-05-06": {"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"}
 #... more events
}

Also you sending the request with the wrong `Content-Type

同样,您也会用错误的“Content-Type”发送请求。

Your request is sent with:

你的要求是:

 Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Not:

不是:

Content-Type: application/json; charset=utf-8;

differences in application/json and application/x-www-form-urlencoded

应用程序/json和应用程序/x-www-form-urlencode的差异。

Added in response to edit of the question:

Use jQuery.ajax instead of jQuery.post and it will stringify the data for you - that way jQuery will take care of browsers which don't have native JSON support.

使用jQuery。代替jQuery ajax。post和它将为您提供数据的stringify,这样jQuery就会处理那些没有本地JSON支持的浏览器。

$.ajax(SaveURL, {
  method: 'POST',
  data: { event: Schedule },
  dataType: 'json'
});

Now that you are sending the correct request type jQuery will merge the post data into params.

现在您已经发送了正确的请求类型,jQuery将把post数据合并到params中。

But this still doesn't fix the issue that Schedule contains the attributes for multiple Events. I would start by creating a simple route which accepts the parameters for a single event. In Rails conventions we call that action create not save.

但是,这仍然不能解决调度包含多个事件属性的问题。我将首先创建一个简单的路由,它接受单个事件的参数。在Rails约定中,我们称该操作创建的不是save。

   class EventsController
     # ... 

     # POST /events
     def create
        @event.new(params[:event])
        if (@event.save) 
           render json: @event, status: :created
        else
           # ... what do we do if validation fails?
        end
     end

     # ...  

     private 

     def create_params
        params.permit(:event).allow(:available, :bind, :info, :notes, :price, :promo, :status)
     end  
   end

You can generate a full set of restful routes for events by adding this to your config/routes.rb:

您可以为事件生成完整的restful路由,并将其添加到配置/路由。

resources :events

which generates the following routes:

产生以下路线:

    Prefix Verb   URI Pattern                Controller#Action
    events GET    /events(.:format)          events#index
           POST   /events(.:format)          events#create
 new_event GET    /events/new(.:format)      events#new
edit_event GET    /events/:id/edit(.:format) events#edit
     event GET    /events/:id(.:format)      events#show
           PATCH  /events/:id(.:format)      events#update
           PUT    /events/:id(.:format)      events#update
           DELETE /events/:id(.:format)      events#destroy

At your skill level I would not bother trying to create a controller action which creates several Events at once, and I'm not going to instruct how to do it here since it would be really lengthy.

在您的技能水平上,我不会费心去创建一个控制器动作,它会同时创建多个事件,而且我不会在这里指导如何做,因为它会很长。

#1


0  

You haven't detailed how you are actually sending the JSON request but two things are going wrong:

您还没有详细说明如何发送JSON请求,但有两件事情正在出错:

Your save action expects a hash with the key event with:

您的save操作预期与关键事件的散列:

{
  event: {
    title: "foo"
    # more attributes ...
  }
}

But you're trying to send the parameters for several dates at the same time.

但是,您尝试同时发送多个日期的参数。

event:{ 
 "2015-05-06": {"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"}
 #... more events
}

Also you sending the request with the wrong `Content-Type

同样,您也会用错误的“Content-Type”发送请求。

Your request is sent with:

你的要求是:

 Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Not:

不是:

Content-Type: application/json; charset=utf-8;

differences in application/json and application/x-www-form-urlencoded

应用程序/json和应用程序/x-www-form-urlencode的差异。

Added in response to edit of the question:

Use jQuery.ajax instead of jQuery.post and it will stringify the data for you - that way jQuery will take care of browsers which don't have native JSON support.

使用jQuery。代替jQuery ajax。post和它将为您提供数据的stringify,这样jQuery就会处理那些没有本地JSON支持的浏览器。

$.ajax(SaveURL, {
  method: 'POST',
  data: { event: Schedule },
  dataType: 'json'
});

Now that you are sending the correct request type jQuery will merge the post data into params.

现在您已经发送了正确的请求类型,jQuery将把post数据合并到params中。

But this still doesn't fix the issue that Schedule contains the attributes for multiple Events. I would start by creating a simple route which accepts the parameters for a single event. In Rails conventions we call that action create not save.

但是,这仍然不能解决调度包含多个事件属性的问题。我将首先创建一个简单的路由,它接受单个事件的参数。在Rails约定中,我们称该操作创建的不是save。

   class EventsController
     # ... 

     # POST /events
     def create
        @event.new(params[:event])
        if (@event.save) 
           render json: @event, status: :created
        else
           # ... what do we do if validation fails?
        end
     end

     # ...  

     private 

     def create_params
        params.permit(:event).allow(:available, :bind, :info, :notes, :price, :promo, :status)
     end  
   end

You can generate a full set of restful routes for events by adding this to your config/routes.rb:

您可以为事件生成完整的restful路由,并将其添加到配置/路由。

resources :events

which generates the following routes:

产生以下路线:

    Prefix Verb   URI Pattern                Controller#Action
    events GET    /events(.:format)          events#index
           POST   /events(.:format)          events#create
 new_event GET    /events/new(.:format)      events#new
edit_event GET    /events/:id/edit(.:format) events#edit
     event GET    /events/:id(.:format)      events#show
           PATCH  /events/:id(.:format)      events#update
           PUT    /events/:id(.:format)      events#update
           DELETE /events/:id(.:format)      events#destroy

At your skill level I would not bother trying to create a controller action which creates several Events at once, and I'm not going to instruct how to do it here since it would be really lengthy.

在您的技能水平上,我不会费心去创建一个控制器动作,它会同时创建多个事件,而且我不会在这里指导如何做,因为它会很长。