【问题标题】:How to pass parameters through link_to如何通过link_to传递参数
【发布时间】:2016-08-21 00:49:35
【问题描述】:

Rails 版本。 5.0.0.1

我想通过投资组合 SHOW 页面中的 link_to 创建和分配一个新属性。该链接应将portfolio_id作为参数传递,并在完成剩余的财产表格后保存。

我已经多次看到这个问题被问到,但由于某种原因,在我自己的应用程序中应用正确答案不起作用。任何帮助将不胜感激,谢谢!

# portfolio show.html.erb

<%= link_to 'Add New Property To This Portfolio', new_property_path(:portfolio_id => @portfolio.id) %>

# properties controller

def new
@portfolio = :portfolio
@property = Property.new(params[:portfolio_id => @portfolio])
end

# portfolio model

has_many :properties

# property model

belongs_to :portfolio
accepts_nested_attributes_for :portfolio

【问题讨论】:

    标签: ruby-on-rails ruby associations


    【解决方案1】:

    您可以很好地传递参数,但您没有正确阅读它们。您当前的代码:

    def new
      @portfolio = :portfolio
      @property = Property.new(params[:portfolio_id => @portfolio])
    end
    

    应改为:

    def new
    
      # Rails stores params passed through a link_to in the params
      # hash, like any other parameter
    
      @portfolio = params[:portfolio]
      @property = Property.new(params[:portfolio_id => @portfolio])
    end
    

    您的代码还有一些其他问题可能需要解决:

    1) 您有一个名为 @portfolio 的字段,但它包含一个 id。通常,像这样的普通名称将存储Portfolio 对象的实例。当字段存储id 时,将_id 附加到末尾。它可以帮助人们了解该领域的内容,并很好地猜测数据类型(对于 Ruby 等脚本语言很重要);

    2) 您确定要让您的link_to 转到new 方法吗?当有人使用另一条路径到达new(如在浏览器中输入 URL)而不设置portfolio_id 时会发生什么?你的代码不会出错吗?

    3) 你确定你可以只用portfolio_id 创建一个Property 对象吗?通常,您会将property_params 传递给新方法以创建新的Property。

    这些都是你应该在考虑一段时间后在不同的问题中解决的问题,但是现在应该解决通过link_to 传递参数的问题。

    【讨论】:

      【解决方案2】:

      我认为您需要在portfolio 模型中接受nested_attributes 的property 模型。然后,从投资组合的显示页面,您可以使用link_to_add 方法为特定的portfolio 添加property。

      投资组合模型

      has_many :properties
      accepts_nested_attributes_for :properties, :allow_destroy => true,, reject_if: :all_blank
      

      属性模型

      belongs_to :portfolio
      

      PortfoliosController.rb

      ##Build in new method:
      
      def new
        @portfolio_object = Portfolio.new
        @portfolio_object.properties.build
      end
      

      在私有方法中接受嵌套属性

      private
      
      def portfolio_params      
        params.require(:portfolio).permit(:list_of_portfolio_parameters, properties_attributes: [ :list_of_properties_parameters, :_destroy ])
      end
      

      然后在 Portfolio new 方法的 html 页面中构建 property 属性。希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-09
        • 2011-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多