我正在尝试将我的消息控制器嵌入到我的频道控制器中。但是当我转到我的消息视图时,我收到错误“无法找到没有id的频道”
class MessagesController < ApplicationController
def index
@channel = Channel.find(params[:channel_id])
@messages = @channel.messages
end
def new
@channel = Channel.find(params[:channel_id])
@message = @channel.messages.build
end
def create
@channel = Channel.find(params[:channel_id])
@message = @channel.messages.build(params[:message])
if @message.save
flash[:notice] = "Successfully created message."
redirect_to channel_url(@message.channel_id)
else
render :action => 'new'
end
end
def edit
@message = Message.find(params[:id])
end
def update
@message = Message.find(params[:id])
if @message.update_attributes(params[:message])
flash[:notice] = "Successfully updated message."
redirect_to channel_url(@message.channel_id)
else
render :action => 'edit'
end
end
def destroy
@message = Message.find(params[:id])
@message.destroy
flash[:notice] = "Successfully destroyed message."
redirect_to channel_url(@message.channel_id)
end
end
频道控制器
class ChannelsController < ApplicationController
def index
@channels = Channel.find(:all)
end
def show
@channel = Channel.find(params[:id])
@message = Message.new(:channel => @channel)
end
def new
@channel = Channel.new
end
def create
@channel = Channel.new(params[:channel])
if @channel.save
flash[:notice] = "Successfully created channel."
redirect_to @channel
else
render :action => 'new'
end
end
def edit
@channel = Channel.find(params[:id])
end
def update
@channel = Channel.find(params[:id])
if @channel.update_attributes(params[:channel])
flash[:notice] = "Successfully updated channel."
redirect_to @channel
else
render :action => 'edit'
end
end
def destroy
@channel = Channel.find(params[:id])
@channel.destroy
flash[:notice] = "Successfully destroyed channel."
redirect_to channels_url
end
end
的routes.rb
SeniorProject::Application.routes.draw do
resources :users
resources :channels, :shallow => true do |channels|
channels.resources :messages
end
root :channels
resources :users, :user_sessions
match 'login' => 'user_sessions#new', :as => :login
match 'logout' => 'user_sessions#destroy', :as => :logout
match ':controller(/:action(/:id(.:format)))'
端
答案 0 :(得分:2)
这里发生的是这一行:
@channel = Channel.find(params[:channel_id])
因为params散列中没有定义的channel_id而失败。我看到你正在使用浅路线,这意味着你的uri可能看起来像这样:
/messages
你需要它看起来像:
/channels/1/messages
尝试将您的网址更改为:
channel_messages_url(@channel)
而不是
messages_url
这是一个猜测btw,可能是因为你定义了你的routes.rb
的方式,这看起来有点奇怪,因为你定义了两次消息路由,一次使用has_many,再次作为a适当的资源。你可能想要这样的东西:
# assuming you need shallow routes
resources :channels, :shallow => true do |channels|
channels.resources :messages
end