简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM