[英]How do I use a URL to link to the create action in Ruby on Rails?
I'm trying to use the following URL to create an object from a bookmarklet: 我正在尝试使用以下URL从书签创建一个对象:
http://localhost:3000/posts?title=Welcome&body=To
but it takes me to the index action. 但这将我带到了索引操作。 How do I get it to point to the create action? 如何获得指向创建动作的信息? I know that both index and create share the same URL, using GET and POST respectively, but I'm not sure how to specify which to use from a URL. 我知道分别使用GET和POST的index和create共享相同的URL,但是我不确定如何指定从URL使用哪个URL。 Thanks for reading. 谢谢阅读。
I'm not sure, but... I think that Rails 3 uses different approach than @FRKT's answer. 我不确定,但是...我认为Rails 3使用的方法与@FRKT的答案不同。 If you create link_to 'whatever', new_somethings_path, :method => :post
it just add some HTML 5 fields: 如果创建link_to 'whatever', new_somethings_path, :method => :post
则只需添加一些HTML 5字段即可:
<a href="/somethings" data-method="post" rel="nofollow">whatever</a>
and it uses js to create a form and submit it. 它使用js创建表单并提交。 Here is some js code from rails.js
: 这是来自rails.js
一些js代码:
function handleMethod(element) {
var method = element.readAttribute('data-method'),
url = element.readAttribute('href'),
csrf_param = $$('meta[name=csrf-param]')[0],
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
element.parentNode.insert(form);
if (method !== 'post') {
var field = new Element('input', { type: 'hidden', name: '_method', value: method });
form.insert(field);
}
if (csrf_param) {
var param = csrf_param.readAttribute('content'),
token = csrf_token.readAttribute('content'),
field = new Element('input', { type: 'hidden', name: param, value: token });
form.insert(field);
}
form.submit();
}
So I think that _method
in params would not work. 因此,我认为params中的_method
无效。
So what you can do? 那你能做什么?
In index
action just add some params checking: 在index
操作中,只需添加一些参数检查:
def index
if params[:title]
@post = Post.new :title => params[:title], :body => params[:body]
if @post.save
... # successful save
else
... # validation error
end
end
... # put normal index code here
end
You can put all createing and saveing object stuff in other method, so your index controller may look cleaner. 您可以将所有创建和保存对象的内容放入其他方法中,以便索引控制器看起来更干净。
You can also create a custom route for this purpose and custom action: 您也可以为此目的和自定义操作创建自定义路线:
# routes
match 'bookmarklet' => 'posts#bookmarklet'
Then put above code from index
action to bookmarklet
action in posts controller. 然后将以上代码从index
动作放置到posts控制器中的bookmarklet
动作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.