【问题标题】:Routing resources issue路由资源问题
【发布时间】: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


【解决方案1】:

Client.invoices 在您的 create 方法中为零,因为它没有在 URL 字符串中接收 ID。

问题似乎出在您的 form_for 中。查看the API documentation 了解如何将form_for 与嵌套资源一起使用。

edit.html.erb

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

请注意,在您的 Invoice#new 控制器操作中,如果您还没有定义 @user@client,则需要定义。

这将生成一个格式正确的路由:

/users/1/clients/2/invoices

这意味着您的 Client.find(params[:client_id]) 应该得到一些东西来建立发票......

【讨论】:

  • 就像我说的,我刚接触 Rails,上个月开始,我的新操作看起来像这样 def new @invoice=Invoice.new @client=Client.find_by(id:params[:id]) @user=current_user 结束
  • ...我觉得没问题。你试过上面的表格吗?结果如何?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 2021-03-17
  • 1970-01-01
相关资源
最近更新 更多