Rails:我拼错了吗?

时间:2012-10-01 18:32:10

标签: ruby-on-rails

您好我正在处理我的第一个项目,并且我正在尝试在执行登录/会话之前先构建功能。我正在尝试创建一个图片专辑网站,其中用户有许多专辑(包含许多图片),专辑访问权限由朋友共享。但是,我注意到我的albums#create

之后

http://localhost:3000/users/18/albums/new(这里没问题)

我被重定向到albums#show

http://localhost:3000/albums/20(问题!!)

不应该在URL中有user_id吗?或者它没有附加到URL的user_id,因为它属于多个用户?这是我的路线:

Pholder::Application.routes.draw do
resources :users do
  resources :albums 
end

resources :albums do
  resources :pictures
end

root :to => "users#index"

以下是我的模型:

用户模型

class User < ActiveRecord::Base

  has_secure_password
  attr_accessible :email, :name, :password, :password_confirmation
  validates_presence_of :password, :on => :create

  validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  validates_length_of :password, :minimum => 5, :on => :create

  has_many :user_albums
  has_many :albums, :through => :user_albums
  accepts_nested_attributes_for :albums

end

专辑模型

class Album < ActiveRecord::Base
  attr_accessible :avatar, :name, :description
  has_many :user_albums
  has_many :users, :through => :user_albums
  has_many :photos
end

相册

class Photo < ActiveRecord::Base
  belongs_to :album
end

专辑控制器

class AlbumsController < ApplicationController

    def index
      @albums = Albums.all

      respond_to do |format|
        format.html
        format.json { render json: @albums }
      end
    end

    def show
      @albums = Album.all
      @album = Album.find(params[:id])
      @photo = Photo.new
    end

    def update
    end

    def edit
    end

    def create
      # @user = User.find(params[:albums][:user_id])
      # @users = User.all
      @album = Album.new(params[:album])
      # @album.user_id = @user.id
      respond_to do |format|
        if @album.save
          format.html { redirect_to @album, notice: 'Album was successfully created.' }
          format.json { render json: @album, status: :created, location: @album}
        else
          format.html { render action: "new" }
          format.json { render json: @album.errors, status: :unprocessable_entity }
        end
      end 
    end

    def new
      @user = User.find(params[:user_id])
      @album = Album.new
    end

    def destroy
    end


end

如果您需要任何其他文件,请告诉我。

1 个答案:

答案 0 :(得分:0)

redirect_to @album行可让您重定向到相关show的{​​{1}}操作。
将此段代码更改为@album之类的代码会使应用重定向到redirect_to users_path的{​​{1}}操作,依此类推。
这取决于保存后您想要的任何行为。

阅读此内容也应该有所帮助:http://guides.rubyonrails.org/routing.html