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:
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 开发者_Python百科share the same URL, using GET and POST respectively, but I'm not sure how to specify which to use from a URL. Thanks for reading.
I'm not sure, but... I think that Rails 3 uses different approach than @FRKT's answer. If you create link_to 'whatever', new_somethings_path, :method => :post
it just add some HTML 5 fields:
<a href="/somethings" data-method="post" rel="nofollow">whatever</a>
and it uses js to create a form and submit it. Here is some js code from rails.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.
So what you can do?
In index
action just add some params checking:
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.
精彩评论