通过Rails中的关联显示has_many

时间:2018-09-27 18:42:34

标签: ruby-on-rails

我有一个小应用程序,允许用户通过添加自己的股票期权来跟踪投资组合的持有量。我建立了以下关联:

stock.rb 
has_many :portfolio_stocks
has_many :portfolios, through: :portfolio_stocks

portfolio.rb 
has_many :portfolio_stocks
has_many :stocks, throough: :portfolio_stocks

portfolio_stocks.rb
belongs_to :stock
belongs_to :portfolio

我在将股票添加到投资组合的新模板中遇到麻烦。这就是stocks_controller动作

def create
portfolio = Portfolio.find(params[:id])
@stock = portfolio.stock.create(stock_params)
end

# GET /stocks/new
def new
@portfolio = Portfolio.find(params[:id])
@stock = Stock.new
end

和我的new.html.erb模板

<center>
<div class="container">
<div class="card-body">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<%= link_to 'Home', portfolios_path %>
</li>
<li class="breadcrumb-item active">Create</li>
</ol>
<%= render partial: "form", locals: {stock: @stock, portfolio: @portfolio}%>   
</div>
</div>
</center>

呈现_form部分

<%= form_for(stock, url: portfolio_stocks_path(portfolio)) do |f| %>
<% if stock.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(stock.errors.count, "error") %> prohibited this portfolio 
from being saved:</h2>
<ul>
<% stock.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.text_field :symbol, autofocus: true, class: 'form-control', 
placeholder: "Enter a ticker" %>
</div>

我不断收到错误

  

找不到带有“ id” =

的投资组合

参数:

{"utf8"=>"✓",
 >"stock"=>{"symbol"=>"FB",
 >"sector"=>"Tech",
 >"high"=>"123",
 >"low"=>"123",
 >"price"=>"123"},
 >"commit"=>"Add Stock",
 >"portfolio_id"=>"1"}

我看不到我在做什么错

1 个答案:

答案 0 :(得分:0)

  

找不到带有“ id” =

的投资组合

按照假设进行操作并查看这段代码portfolio_stocks_path(portfolio)),我相信您正在对portfoliosstocks使用嵌套路由。如果是这样,那就说明了错误的原因。

如果您运行rake routes,则会看到

portfolio_stocks      POST   /portfolios/:portfolio_id/stocks(.:format)        stocks#create
new_portfolio_stock   GET    /portfolios/:portfolio_id/stocks/new(.:format)    stocks#new

这意味着应该使用Portfolio而不是params[:portfolio_id]中的params[:id]访问stocks_controller实例。也就是说,您应该像这样更改newcreate方法

def create
  portfolio = Portfolio.find(params[:portfolio_id])
  @stock = portfolio.stocks.create(stock_params) #fixed the invalid syntax
end

# GET /stocks/new
def new
  @portfolio = Portfolio.find(params[:portfolio_id])
  @stock = Stock.new
end

还请注意,我已将portfolio.stock.create(stock_params)更改为portfolio.stocks.create(stock_params),因为portfolio.stock.create(stock_params)的关联设置方式是无效的语法,并且引发异常