0

尝试使用 nested_form gem 将用户添加到乐队时,我无法从参数访问用户。经过一番调查,我注意到我在控制台中收到了未经许可的参数错误。我需要访问 users_attributes 以便我可以通过控制器中的显示名称在我的数据库中搜索用户。(所以nested_form是添加已经在数据库中的用户,如果有更好的方法请告诉我)

这是来自 rails 控制台的错误:

在 2015-04-29 01:59:03 -0400 为 127.0.0.1 开始 PATCH "/band_steps/videos" 由 BandStepsController#update 作为 HTML 参数处理:{"utf8"=>"✓", "authenticity_token"=>" oA16RrnTw9Tn/7n45jSjrg+Q6vO8q+TxrYRHLOKSJYs=", "band"=>{"users_attributes"=>{"0"=>{"display_name"=>"Tyler", "_destroy"=>"false", "id"= >"330"}}}, "commit"=>"Next", "id"=>"videos"} 频带负载 (0.2ms) SELECT "bands".* FROM "bands" WHERE "bands"."id" = $1 LIMIT 1 [["id", 57]] 不允许的参数:users_attributes (0.1ms) BEGIN Band Exists (0.5ms) SELECT 1 AS one FROM "bands"WHERE (LOWER("bands"."name") = LOWER('asdfsbad') AND "bands"."id" != 57) LIMIT 1 (0.2ms) COMMIT 重定向到http://localhost:3000/band_steps/ music Completed 302 Found in 8ms (ActiveRecord: 1.0ms)

表单部分代码(_form.html.erb):

<%= nested_form_for @band, url: wizard_path do |band_form| %>
    <%= render partial: 'shared/error_messages', locals: {obj: band_form.object} %>
    <%= yield band_form %>
    <%= band_form.submit "Next" %>
<%end%>

member.html.erb 中的代码(调用部分的页面)

<h3> Add members to your band! </h3>
<%= render layout: 'form' do |band_form| %>
    <%= band_form.fields_for :users do |builder| %>
        <%= render 'user_fields', builder:builder %>
    <%end%>
        <p><%= band_form.link_to_add "Add a Member", :users %></p>
    <br>
<%end%>
<%= link_to "skip this step", next_wizard_path %><br>
<%= link_to "Back", previous_wizard_path %>

_user_fields.html.erb 中的代码(呈现用户字段的部分)

<p>
<%= builder.label :display_name, "Display Name" %>
<%= builder.text_field :display_name %>
<%= builder.link_to_remove "Remove this User" %>
</p>

相关频段控制器代码:(我只贴直接涉及的方法以节省阅读时间,我可以根据需要发布所有代码)

创建方法:

def create
    @band = Band.new(band_params)
    @band_params = band_params
    if @band.save
      session[:band_id] = @band.id
      redirect_to band_steps_path
    else
      render :new
    end
 end

强大的参数:

def band_params

    params.require(:band).permit(:name, :location, :about_me, :profile_picture,
   :full_address, :video_link, user_ids: [], genre_ids: [],
   band_video_attributes: [:video_link, :video_name],
    band_music_attributes: [:name, :embed_html], 
    genre_ids: [], users_attributes: [])
end

乐队型号:

has_many :user_bands, dependent: :destroy
has_many :users, through: :user_bands
accepts_nested_attributes_for :users, allow_destroy: true

用户模型:

has_many :user_bands
has_many :bands, through: :user_bands

总结一下代码应该如何工作: Band 表单有用于输入用户显示名称的字段,我在 Band 控制器中访问显示名称。

我花了很多时间查看我的代码,看看我在哪里犯了错误。任何帮助表示赞赏。

4

0 回答 0