rails 新手:如何从视图获取参数到控制器

rails newbie: how to get params from view to controller

这个问题我想了很久。我很确定你会很快发现我的错误。因为我已经阅读了至少十个类似的 threads/questions 和几乎相同的 "problem" 我想我想通了 "the problem" 可能是什么,但不知道如何解决它。

我思考了三个小时后提出的问题: 为什么我的 editview 没有收到 <%= link_to 'bearbeiten', edit_tour_tn_path(@tour, t) % 的参数?

详细:

我正在使用嵌套资源(如入门指南中所述): 一次旅行 has_many tns,一次旅行 belongs_to 一次旅行。

routes.rb

resources :tours do 
  resources :tns  
end

tns_controller.rb

class TnsController < ApplicationController

  def create
   @tour = Tour.find(params[:tour_id])
   @tn = @tour.tns.create(tn_params)
   redirect_to tour_path(@tour)
  end

 def new
  @tour = Tour.find(params[:tour_id])
  @tn = @tour.tns.create(tn_params)
 end

 def index
  @tour = Tour.find(params[:tour_id])
  @tns = @tour.tns.all
 end

def edit
  @tour = Tour.find(params[:tour_id])
  @tn = @tour.tns.find(params[:id])

 if @tn.update(tn_params)
   redirect_to tour_tns_path
 else
   render 'edit'
 end
end

def show
  @tn = Tn.find(params[:id])
end

private
 def tn_params
  params.require(:tn).permit(:vorname, :nachname, :gender, :bdate, :email, :telefon, :schwimmen, :besonderheit, :eek, :fotog, :notfallk, :kkh)
end

end

视图:form_for 片段:

  <%= form_for([@tour, @tour.tns.build]) do |f| %>
   #with many more fields, but i think they aren't relevant for my problem

view: show tour 及其 tns(如教程中的 'show blogpost and comments')

<p> TeilnehmerInnen:
    <table>
    <th>Vorname</th>
    <th>Nachname</th>
    <th>Alter</th>
    <th>Bearbeiten</th>
    <th>Löschen</th>

<tr><% @tour.tns.each do |t| %>
<td><%= t.vorname %> </td>
<td><%= t.nachname %></td>
<td><%= ((DateTime.now - t.bdate)/ 365.25).to_i %> Jahre</td>
<td><%= link_to 'edit', edit_tour_tn_path(tour_id: t) %></td>
<td>#mülleimer verlinken</td>
</tr>   
    <% end %>
 </table>
</p>

如果我点击'bearbeiten' link编辑一个tour_tn,我得到的是流行的

"param is missing or the value is empty: tn"

指的是私有定义 tn_params 东西:

app/controllers/tns_controller.rb:35:in tn_params' app/controllers/tns_controller.rb:22:inedit'

但随着请求与参数一起出现

Parameters:

{"tour_id"=>"3", "id"=>"5"}

我不明白我的编辑表单(呈现上面提到的form_for)是如何获取参数的。

你能不能帮我看看我鼻子前面的那棵树? :>

亲切的问候,

丹尼尔

试试这个:

这会将 id 传递到您的编辑操作中

<td><%= link_to 'edit', edit_tour_tn_path(t) %></td>

如果您想使用

发送一些额外的参数
<td><%= link_to 'edit', edit_tour_tn_path(id: t) %></td>

编辑动作

def edit
  @tour = Tour.find(params[:tn][:tour_id])
  @tn = @tour.tns.find(params[:id])

 if @tn.update(tn_params)
   redirect_to tour_tns_path
 else
   render 'edit'
 end
end