【问题标题】:i am trying out nested resources and not working out我正在尝试嵌套资源但没有解决
【发布时间】:2014-02-08 04:09:07
【问题描述】:

我收到了这个错误

Pages#home 中的 ActionController::UrlGenerationError 显示 C:/Users/jhakas realstate/Desktop/call/app/views/layouts/application.html.erb 其中第 55 行提出:

没有路由匹配 {:controller=>"refills", :action=>"new"} 缺少必需的密钥:[:user_id, :wallet_id] 提取的源代码(在 #55 行附近): 52 53 54 55 56 57 58

         <li class="divider-vertical"></li>
         <% if user_signed_in? %>
           <li><%= link_to "Dashboard", new_user_wallet_refill_path %></li>
           <li><%= link_to "Edit Profile", edit_user_registration_path %></li>
           <li><%= link_to "Logout", destroy_user_session_path, method: :delete %></li>
         <% else %>

和我在路线中的资源

resources :users do  
  resources :wallets do     
    resources :refills
  end
end

我的钱包控制器是

def create
  @wallet = Wallet.new([:user_id]wallet_params)

  respond_to do |format|
    if @wallet.save
      format.html { redirect_to @wallet, notice: 'Wallet was successfully created.' }
      format.json { render action: 'show', status: :created, location: @wallet }
    else
      format.html { render action: 'new' }
      format.json { render json: @wallet.errors, status: :unprocessable_entity }
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    这些行需要父资源的 ID 才能工作:

    <li><%= link_to "Dashboard", new_user_wallet_refill_path %></li>
    <li><%= link_to "Edit Profile", edit_user_registration_path %></li>
    

    你应该使用这样的路径:

    new_user_wallet_refill_path(@user, @wallet)
    edit_user_registration_path(@user) # This one might not need the @user object ... I'm not a devise expert.
    

    【讨论】:

    • 我做了 'new_user_wallet_refill_path(@user, @wallet)' 我在 Pages#home 中得到 ActionController::UrlGenerationError
    • 你有@user@wallet 实例变量吗?
    • 不知道怎么做以及为什么
    • 在您遇到问题的视图的控制器操作中,任何实例变量(以@ 符号开头)都可以在您的视图中使用。在您的控制器中,设置@user = User.find(params[:id]) 或者您正在寻找用户。与@wallet 相同,一切正常。
    • 好的,所以我需要在控制器中设置实例变量才能在视图中访问它。所以如果我有用户控制器,我可以为其他模型创建实例变量等等?
    【解决方案2】:

    当您将钱包资源嵌套在用户资源中时,我相信它会破坏您在 create 方法中使用的 redirect_to @wallet 约定。尝试使用实际路径

    redirect_to user_wallet_path(@wallet.user, @wallet)
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多