简体   繁体   English

如何在Rails控制器中的show action中获取值

[英]How to get values in show action in rails controller

I would like to have access to the parameters in nested attributes..... Below is the code. 我想访问嵌套属性中的参数.....下面是代码。

<%= link_to "Invoice", user_invoice_path(@user, invoice) %>

How do I access the user and invoice in the Invoice controller show action. 如何在“发票”控制器中显示用户和发票的操作。

def show
  @user = User.find(params[:user_id])
  @invoice = Invoice.find(params[:id])
end 

User Model: 用户模型:

class User < ActiveRecord::Base
  has_many :invoices
end

Invoice Model: 发票型号:

class Invoice < ActiveRecord::Base
  belongs_to :user
end

I know how it works when it is not nested.... Can anyone, please help? 我知道它不嵌套时如何工作。...任何人都可以,请帮忙吗?

If I understand correctly, you can't find the @user or @invoice in this way. 如果我理解正确,则无法以这种方式找到@user@invoice

Please debug your show action and you will find params as follows, 请调试您的show动作,您将发现以下params

{"action"=>"show", "controller"=>"invoices", "user_id"=>"307", "id"=>"359"}

So now write your show action something like, 所以现在写你的表演动作,

def show
  @invoice = Invoice.find(params[:id])
  @user = User.find(params[:user_id])
end

There may be better ways to find the objects in the controller action. 在控制器动作中可能有更好的方法来找到对象。 But this is the basic approach you will have to consider instead of what you tried. 但这是您必须考虑的基本方法,而不是您尝试过的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM