在频道视图上嵌套消息

时间:2010-11-27 19:30:34

标签: ruby-on-rails postgresql windows-7

我正在尝试显示属于该频道索引页面上每个频道的所有消息,有没有一种简单的方法可以做到这一点?

    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

&安培;

MyApp::Application.routes.draw do

  resources :users
  resources :channels , :has_many => :messages, :shallow => true
  resources :messages , :only => [:index]
  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)))'
  #root :to => 'channels#index', :as => :listchannels



end

1 个答案:

答案 0 :(得分:1)

假设有两个模型Channel和Message,其中一个频道有很多消息,你可以这样做:

# controller
@channel = Channel.find(params[:channel_id])
@messages = @channel.messages

# index.html.erb
<% @messages.each do |message| %>
  <%=h message.content %><br>
<% end %>

其中contentMessage

的某个属性