I have a model called 'links.' In routes.rb I have defined it with:
resources :links
I have a form in /links/new it looks like this:
<%= form_for :links do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :url %>
<%= f.url_field :url, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit :"Create Link", class: "btn btn-primary" %>
</div>
<% end %>
When I submit it, I get the error No route matches [POST] "/links/new"
even though this is in the list of routes:
new_link_path GET /links/new(.:format) links#new
What is the problem?
Try this:
<%= form_for(Link.new) do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :url %>
<%= f.url_field :url, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Create Link", class: "btn btn-primary" %>
</div>
<% end %>
add NEW route method in controller Controller
def new
@link = Link.new
end
When you will visit to links/new then new route method will call and render links/new template. so add below code in tamplete
<% form_for(:link, @link, :url => {:action => 'create'}) do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :url %>
<%= f.url_field :url, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Create Link", class: "btn btn-primary" %>
</div>
<% end %>
and handle create request in create action of link controller
def create
@link = Link.new params[:link]
if @link.save
redirect_to :action => 'show', :id => @link.id
else
render :action => 'new'
end
end
dont forget to allow params for link in controller. this is a proper way to create a new record in ror
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.