如何通过link_to传递参数到
Rails ver。 5.0.0.1如何通过link_to传递参数到
我想通过组合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
你传递的参数很好,但你没有正确读取它们。您当前的代码:
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)你确定你可以创建一个Property
对象只有一个portfolio_id
?通常情况下,您将通过property_params
新方法创建一个新的Property
。
这些东西都是你应该在不同的问题中解决的所有事情,一旦你想了一会儿,但现在应该通过link_to
来传递参数。
我觉得你需要接受nested_attributes
的property
模型portfolio
模型。然后,从投资组合的展示页面,您可以使用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
属性。希望它能帮助你。