【发布时间】:2016-03-09 23:16:41
【问题描述】:
我有一个 Rails 项目,其中有一个 Customer 表和一个 Ticket 表。关系是 Ticket has_many :customers 和 Customer belongs_to :ticket。
在我的客户索引页面上,我列出了所有具有创建、更新和删除选项的客户。所有这一切都很好。但是,我现在想要做的是创建另一个按钮(在每个客户的索引页面上),单击该按钮时,它会创建一个票证,并将所选客户添加到票证中。我目前在模型中设置了关系。我的第一个想法是为表格中的每个客户添加一个按钮,并让该按钮向我的门票控制器中的创建函数发出发布请求,如下所示
post 'tickets', to: 'tickets#create', as: 'create_ticket'
当调用票证功能时,我假设我会从发布请求中获取客户,创建一个新票证,并以某种方式使票证通过我的关系获得客户的所有权。 这是我的创建函数。
def create
@customer = Customer.find(params.require(:customer))
end
到目前为止,我只能得到类似“ActionController::ParameterMissing in TicketsController#create”的错误 参数缺失或值为空:客户”
这是我的 index.html.erb 中发出帖子请求的链接
<%= link_to "add to tickets", create_ticket_path(c), method: :post %>
任何帮助将不胜感激!提前致谢。
我最近刚刚尝试以与我的编辑功能类似的方式实现它。
我在 index.html.erb 中的链接现在是
<%= link_to "add to tickets", create_ticket_path(c) %>
我现在的路线是
get 'tickets/:id/create', to: 'tickets#create', as: 'create_ticket'
当我点击按钮时,这是我的浏览器指向的网址
http://localhost:3000/tickets/1/create
我在门票控制器中的创建功能现在是
def create
@customer = Customer.find(params[:id])
end
这是我现在得到的错误:
模板丢失 缺少模板票证/创建,使用 {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}。在以下位置搜索:*“/vagrant/ServiceManager/app/views”*“/home/vagrant/.rvm/gems/ruby-2.2.1/gems/devise-3.5.2/app/views” 提取的源代码(第 46 行附近):
def find(*args)
find_all(*args).first || raise(MissingTemplate.new(self, *args))
end
def find_all(path, prefixes = [], *args)
<% @tickets.each do |t| %>
<tr>
<td><%= t.description %></td>
<td><%= t.customers.name %></td>
</tr>
<% end %>
这是我的模型关联:
class Ticket < ActiveRecord::Base
has_many :customers
end
class Customer < ActiveRecord::Base
belongs_to :ticket
end
这里是index.html.erb的内容
描述: 名称: 客户
名字应该是鲍勃。它为所有客户做同样的事情。
【问题讨论】:
-
您能发布
link_to生成的网址吗?您没有使用customer键传递 json 对象,这就是您收到错误的原因。通常你会有一个带有 customer['id] 属性的表单,它是一个隐藏字段,然后让提交按钮成为实际点击的按钮或类似的东西。 -
@CWitty 我刚刚编辑了这个问题。我所有的编辑都在水平线下方。
-
所以有了那个,你并没有告诉它重定向或渲染任何东西,所以它正在寻找一个它找不到的模板。尝试
redirect_to @customer或其他东西,应该可以解决它 -
@CWitty 好的,成功了!我很感激。所以,我仍然需要创建票证。我遵循了有关如何建立关联的教程,但我仍然不确定实际创建带有客户参考的票证所需的代码。你也可以在这里帮忙吗?
-
我会在答案栏发帖
标签: ruby-on-rails ruby