Rails嵌套资源路由

时间:2012-05-04 03:30:25

标签: ruby-on-rails nested-routes

我对rails很新,我不认为我完全理解了路由。当我尝试访问编辑操作时,出现以下错误:

ActiveRecord::RecordNotFound in StoreController#show

Couldn't find Gear with id=edit
Rails.root: /Users/dave/rails_projects/outdoor

Application Trace | Framework Trace | Full Trace
app/controllers/store_controller.rb:7:in `show'
Request

Parameters:

{"user_id"=>"104",
 "id"=>"edit"}
Show session dump

Show env dump

Response

Headers:

None

以下是我的观点,其中包含引发此错误的链接:

    <li><%= link_to "Store Appearance", edit_user_store_path(@user) %></li>

这是我的嵌套路线:

  resources :users do
    resources :store
  end

这是我的控制器

class StoreController < ApplicationController
  def index
     @store = current_user.gears.paginate(page: params[:page])
  end

  def show
     @gears = Gear.find(params[:id]).user.gears.paginate(page: params[:page])
  end

  def edit
  end

  def update
  end
end

模型商店

class Store < ActiveRecord::Base
  attr_accessible :storeimage, :storename
  belongs_to :user

  validates :user_id, :presence => true

end

模型用户

class User < ActiveRecord::Base

  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :userimage, :remove_userimage
  has_secure_password
  has_many :gears
  has_many :comments, :dependent => :destroy 
  has_one :store, :dependent => :destroy
  before_save :create_remember_token
  require 'carrierwave/orm/activerecord'
  mount_uploader :userimage, UserpicUploader

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :first_name,  presence: true,
                          length:  {:maximum => 50 }
  validates :last_name,  presence: true,
                         length:  {:maximum => 50 }
  validates :email,      presence: true,
                         format:  {:with => email_regex},
                         uniqueness:  {:case_sensitive => false}
  validates :password,   presence: true,
                         confirmation: true,
                         length: {within: 6..40}

  include Tire::Model::Search
  include Tire::Model::Callbacks

  def name
   first_name + " " + last_name
  end

  private

    def create_remember_token
        self.remember_token = SecureRandom.urlsafe_base64
    end

end

请帮忙。

1 个答案:

答案 0 :(得分:1)

当您访问嵌套在user_id下的id对象时,您需要在网址中同时传递storeuser参数,因此您的网址应该是像这样:

/users/1/stores/3/edit

对战:

/users/1/stores/edit

您还需要将这两个作为参数传递给路径助手,即:

edit_user_store_path(@user, @store)