Rails 4 how to create and listing in the same page -
i have model product , want create , list under text_field
in controller
class productcontroller < applicationcontroller def buy @product = product.new(product_params) respond_to |format| if @product.save format.html { redirect_to @product, notice: 'product added.'} else format.html { redirect_to @product, notice: 'failed added.'} end end end private def product_params params.permit(:name, :description) end
end
and view
<%= simple_form_for @product, :url => { :controller => 'product', :action => 'buy'} |f| %> <%= f.input :name %> <%= f.input :description %> <%= f.button :label => 'buy', :class => 'btn add-product btn-primary' %> <% end %>
and try list in same view
<% @products.each |product| %> <%= product.name %> <%= product.description %>
and script
<script> $('.add-product').click(function(){ $('.product').clone().first().appendto('.container'); })
i'm not sure code can run or not cuz got problem
undefined method `model_name' nilclass:class
in <%= simple_form_for @product, :url => { :controller => 'product', :action => 'buy'} |f| %>
my question append form partial in new view of same model in rails can't use %input{:name => "model[][name]"} input
can me how fix code thanks~
@pruduct
typo. make @product
. fix it?
based on comments.
class productcontroller < applicationcontroller def index @products = product.all @product = produc.new end def buy @product = product.new(product_params) respond_to |format| if @product.save format.html { redirect_to products_path, notice: 'product added.'} else format.html @products = product.all flash.now[:error] = 'failed add product' render action: 'index' end end end end end
had change redirect on failed since if didn't save won't have id, , won't able redirect it.
then in index.html.erb
view
<%= simple_form_for @product, :url => { :controller => 'product', :action => 'buy'} |f| %> <%= f.input :name %> <%= f.input :description %> <%= f.button :label => 'buy', :class => 'btn add-product btn-primary' %> <% end %> <% @products.each |product| %> <%= product.name %> <%= product.description %> <% end %>
i think should asking.
Comments
Post a Comment