How to make 'create' method be useable from outside

心不动则不痛 提交于 2020-01-17 07:30:13

问题


this is my method

def add
    @result
    @log = Log.new(params[:log])
    if @log.save
      result = "success";
    else
      result = "fail";
    end
    render :json => result
end

and this is my routes.rb

match "/logs/add/:value/:category/:note/:own" => "logs#add"

when i try putting this URL:

http://localhost:3000/logs/add/338/testcat/testnote/testown

and it returns the json correctly and new item was added to the database but all of the fields(value,category,note,own) are null.

please help :(


I've already solved the above problem, but

What if i want to create multiple objects by sending from 1 url to my ruby. Ex:

localhost:3000/logs/add/338/testcat/testnote/testown

The above request will create only 1 log to my database If I want to create many logs by using the above solution, I have to send one url for one log. I want my ruby to be able to create multiple logs from 1 url. I mean that I can create many logs by sending only one url to the server. What routing,method,url should be? (I heard something about "url/add/param1&&param2" ?


回答1:


You're calling Log.new(params[:log]) but there isn't a log parameter in the request.

You can fix this by updating your #new call:

@log = Log.new({
    :value => params[:value],
    :category => params[:category],
    :note => params[:note],
    :own => params[:own]
})

but bear in mind that you will then have a GET request which changes your database state. This is potentially a security flaw, because a potential attacker could get you to update your database just by following a link (from their website, in an email etc). This could even be a problem without a malicious attacker - Google will happily follow GET links - and even if you hide your site behind a login, it's not impossible to think of a situation where Chrome may try and speed up your browsing session by "intelligently" preloading a link it spots in the page before you click it.

Generally all of your data-changing actions should be limited to POST requests




回答2:


When you specify parameters like :note in your route its value will be passed in params hash, but it won't be automatically passed to your model.

params hash will have keys :value, :category, :note, :own but not :log. To initialize properly your model you can do smth like that:

Log.new :value    => params[:value],
        :category => params[:category],
        :note     => params[:note],  
        :own      => params[:own]

or just

Log.new params

but in last case you should ensure that there are no other parameters in params hash but attributes for your model.



来源:https://stackoverflow.com/questions/8455418/how-to-make-create-method-be-useable-from-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!