gpt4 book ai didi

ruby-on-rails-3 - Ruby on Rails 将 id 传递给新的创建表单

转载 作者:行者123 更新时间:2023-12-02 02:06:56 25 4
gpt4 key购买 nike

好吧,我搜索了高低,阅读了教程,观看了视频,但我仍然没有找到任何地方。我在这里读过类似的问题,但问题更复杂或缺乏答案 - 所以这里是......

我有模型帐户和发票。显示帐户时,我想要一个指向与该帐户相关的“创建新发票”的链接。 (后来我实际上想要一个选择字段来在创建发票时选择一个帐户,但我会把它留给另一个痛苦)。

这是我的模型...
帐户:

class Account < ActiveRecord::Base
attr_accessible :name, :invoice
attr_accessible :name, :invoice
has_many :invoices
end

和发票:
class Invoice < ActiveRecord::Base
belongs_to :account
attr_accessible :amount_pretax, :amount_total, :date_sent, :project, :status, :tax, :account, :account_id
end

现在,在我的/views/accounts/show.html.erb
<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= @account.name %>
</p>
<%= link_to 'New Invoice', new_invoice_path(:account_id=>@account.id) %>
<%= link_to 'Edit', edit_account_path(@account) %> |
<%= link_to 'Back', accounts_path %>

所以,发生的事情是,当我单击“新发票”链接时,它会显示新表单,帐户字段填充有以下奇怪的文本: #<Account:0x10fe16bc0>然后当我提交表单时,我收到此错误:
ActiveRecord::AssociationTypeMismatch in InvoicesController#create
声明如下: Account(#2281084000) expected, got String(#2267210740)伴随着这个:
app/controllers/invoices_controller.rb:45:in `new'
app/controllers/invoices_controller.rb:45:in `create'

这是发票 Controller 中的内容:
def new
@invoice = Invoice.new(:account_id => params[:account_id])
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @invoice }
end
end

def create
@invoice = Invoice.new(params[:invoice])
....
end

以上是我认为我出错的地方,但是现在如何放置这些线条超出了我的范围。我完全是一个初学者,解决此功能的任何帮助肯定会教会我很多东西。

谢谢你的时间。

最佳答案

当您单击 New invoice/views/accounts/show 上的链接页,我想您希望您的新发票属于该帐户。

因此,在您的表单中,您不必让用户选择帐户。例如,您可以用 hidden_field 替换相应的字段。 :

<%= f.hidden_field :account_id, :value => params[:account_id] %>

也在 new Controller 的 Action ,替换 @invoice = Invoice.new(:account_id => params[:account_id])来自 @invoice = Invoice.new
希望这可以帮助。

关于ruby-on-rails-3 - Ruby on Rails 将 id 传递给新的创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14569590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com