Ruby on rails 尝试将id传递到下一个表单时遇到问题

Ruby on rails 尝试将id传递到下一个表单时遇到问题,ruby-on-rails,ruby-on-rails-4,model-view-controller,associations,Ruby On Rails,Ruby On Rails 4,Model View Controller,Associations,我有一个付款和访问的模型。我已将它们关联到如下所示的模型中。一次访问只能有一次付款 我已经设置了一个用户填写一个访问表单,然后一旦完成就被重定向到付款表单。我希望的是,访问id自动传递到下一页访问id表单中的隐藏字段中 class Visit < ActiveRecord::Base has_one :payment end class Payment < ActiveRecord::Base belongs_to :visit end 课堂访问

我有一个付款和访问的模型。我已将它们关联到如下所示的模型中。一次访问只能有一次付款

我已经设置了一个用户填写一个访问表单,然后一旦完成就被重定向到付款表单。我希望的是,访问id自动传递到下一页访问id表单中的隐藏字段中

class Visit < ActiveRecord::Base
has_one :payment
end

class Payment < ActiveRecord::Base
belongs_to :visit
end
课堂访问

这似乎是相当基本的,只是我似乎不能正确地将我的思想围绕在联想上。我四处搜索,看到一些人试图解释,但无论我尝试什么都不能正常工作。提前谢谢

一种方法是,在您的
visitcontroller

def create
  @visit = Visit.create(visits_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    @payment = @visit.build_payment
  end
end
def create
  @visit = Visit.create(visit_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    redirect_to new_payment_path(visit_id: @visit.id)
  end
end
def new
  @visit = Visit.find(params[:visit_id])
  @payment = @visit.build_payment
end
然后在您的
访问/create.html.erb
中,只需

<%= form_for @payment do |f| %>
  <%= f.hidden_field :visit_id %>
<% end %>
这将生成以下路由:

GET /visits/:visit_id/payments/new
然后在
访问控制器中

def create
  @visit = Visit.create(visits_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    @payment = @visit.build_payment
  end
end
def create
  @visit = Visit.create(visit_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    redirect_to new_payment_path(visit_id: @visit.id)
  end
end
def new
  @visit = Visit.find(params[:visit_id])
  @payment = @visit.build_payment
end
在您的
PaymentsController中

def create
  @visit = Visit.create(visits_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    @payment = @visit.build_payment
  end
end
def create
  @visit = Visit.create(visit_params)
  if !@visit.save
    render :new, error: "Something went wrong"
  else
    redirect_to new_payment_path(visit_id: @visit.id)
  end
end
def new
  @visit = Visit.find(params[:visit_id])
  @payment = @visit.build_payment
end
在您的
payments/new.html.erb
中,不要忘记

<%= form_for @payment do |f| %>
  <%= f.hidden_field :visit_id %>
<% end %>


现在你有了它。。。如果这没有任何意义,请告诉我。

这很有意义,但是它正在退出@visit.payment.build?不确定到底发生了什么错误是:nil的未定义方法“build”:nilclass抱歉,这是一个has_one关系,所以它是@visit.build_,我现在正在更新我的答案。查看文档以获取更多信息()有没有可能给我一个构建正在做什么的概述?它只是创建关系类的一个新实例。当使用has_one/belishing_构建时,将构建类“other”的新对象并设置调用方的id。当使用has_many/belish_to'other'时,build将在集合上执行相同的操作。这很有意义。明白了。你有时间偶然问另一个问题吗?与前一个无关。我现在已经开始工作了