ruby on rails - Routing resources issue -


in invoice app,i have 3 models associated each other,but problem how add invoices resource clients?

user.rb

class user < activerecord::base     has_many :clients , dependent: :destroy     has_many :invoices , through: :clients end  class invoice < activerecord::base   belongs_to :client   belongs_to :user end  class client < activerecord::base     belongs_to :user     has_many :invoices end 

routes:

resources :users   resources :clients     resources :invoices   end end 

but each time try create new invoice, error:

"nomethoderror in invoicescontroller#create undefined method `invoices' nil:nilclass"

controller's create action:

def create     @client = client.find_by(id:params[:client_id])     @invoice = @client.invoices.new(attr_params) end 

how create invoice each client without error above?

the edit view:

         <%= form_for :invoice , url:{action:"create"} |f| %>          <td><%= f.text_field :item_code %></td>                 <td><%= f.text_field :description %></td>                 <td><%= f.text_field :qty %></td>                 <td><%= f.text_field :unit %></td>                 <td><%= f.text_field :total %></td>                              </tr>         </table>         <%= f.submit 'preview'%>         <% end %> 

attr_params:

private    def attr_params     params.require(:invoice).permit(:item_code,:description,:qty,:unit,:total)  end 

my edit action:

@invoice=invoice.new @client=client.find_by(id:params[:id]) 

parameters:

(@siim)

{"utf8"=>"✓",  "authenticity_token"=>"hy0lhylr594o7zutkao3gf3kj9kt/2loqhhw9saq5ha=",  "invoice"=>{"item_code"=>"08675",  "description"=>"food item",  "qty"=>"6",  "unit"=>"$123",  "total"=>"$738"},  "commit"=>"preview"}                                                                                 

def new

 @invoice=invoice.new   @client=client.find_by(id:params[:id])   @user=current_user 

end

this new action,please guys new rails,just month old.

client.invoices nil in create method because it's not receiving id in url string.

the issue appears in form_for. check out the api documentation how use form_for nested resources.

edit.html.erb

<%= form_for [@user, @client, @invoice] |f| %>   <%# fields %>   <%= f.submit 'preview'%> <% end %> 

note in invoice#new controller action, need define @user , @client if aren't already.

this generate correctly formatted-route:

/users/1/clients/2/invoices

which means client.find(params[:client_id]) should build invoice off of..


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -