【发布时间】:2015-09-30 17:02:03
【问题描述】:
在我的发票应用中,我有三个相互关联的模型,但现在的问题是如何将发票资源添加到客户端?
用户.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
路线:
resources :users do
resources :clients do
resources :invoices
end
end
但每次我尝试创建新发票时,都会收到此错误:
"InvoicesController#create 中的 NoMethodError nil:NilClass 的未定义方法“发票”
控制器的创建动作:
def create
@client = Client.find_by(id:params[:client_id])
@invoice = @client.invoices.new(attr_params)
end
如何为每个客户创建发票而不出现上述错误?
编辑视图:
<%= form_for :invoice , url:{action:"create"} do |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
我的编辑操作:
@invoice=Invoice.new
@client=Client.find_by(id:params[:id])
参数:
(@Siim)
{"utf8"=>"✓",
"authenticity_token"=>"HY0lhylr594o7zuTkaO3gf3KJ9kt/2LoqHHW9saQ5hA=",
"invoice"=>{"item_code"=>"08675",
"description"=>"food item",
"qty"=>"6",
"unit"=>"$123",
"total"=>"$738"},
"commit"=>"preview"}
定义新
@invoice=Invoice.new
@client=Client.find_by(id:params[:id])
@user=current_user
结束
这是我的新动作,请大家对 Rails 不熟悉,才一个月大。
【问题讨论】:
-
您需要提供更多信息才能帮助您。您的视图看起来如何以及您要提交的参数是什么。
-
我刚刚更新了我的代码@Siim
-
请同时发布传递给您的创建操作的参数。要查看它们,只需将
puts params.inspect作为您操作的第一行,然后查看输出是什么。
标签: ruby-on-rails