在我的发票应用程序中,我有三个相互关联的模型,但现在的问题是如何将发票资源添加到客户端?
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
但每次我尝试创建新发票时,都会收到此错误:
&#34; InvoicesController中的NoMethodError #create 未定义的方法`发票&#39;为零:NilClass&#34;
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 %>
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])
(@西姆)
{"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
端
这是我的新动作,请大家刚刚开始使用rails,仅仅一个月。
答案 0 :(得分:0)
Private Sub tree_DrawNode(sender As Object, e As DrawTreeNodeEventArgs)
If e.Node.Level = 1 Then
HideCheckBox(e.Node)
e.DrawDefault = True
Else
TextRenderer.DrawText(e.Graphics, e.Node.Text, _
e.Node.TreeView.Font, e.Bounds, Color.Black, Color.White)
End If
End Sub
在您的create方法中为nil,因为它没有在URL字符串中收到ID。
问题似乎出现在您的form_for中。查看the API documentation了解如何将Client.invoices
用于嵌套资源。
<强> edit.html.erb 强>
form_for
请注意,在<%= form_for [@user, @client, @invoice] do |f| %>
<%# fields %>
<%= f.submit 'preview'%>
<% end %>
控制器操作中,如果您尚未定义Invoice#new
和@user
,则需要定义。
这将生成格式正确的路线:
@client
这意味着您的/users/1/clients/2/invoices
应该可以通过...