0

I have three models (listed below): Users, Threads, and a join called Publications.

I'm successfully listing all of a user's publications, and I'm showing the publication's user_id and thread_id.

Instead of listing the publication's information, I'd like to display the thread's name for each publication, using each publication's thread_id.

Below is my user model:

class User < ActiveRecord::Base

    devise :database_authenticatable, :registerable, :confirmable,
           :recoverable, :rememberable, :trackable, :validatable

    attr_accessible :email, :password, :password_confirmation, 
                    :remember_me, :username, :profile_image, 
                    :first_name, :last_name

    has_many :publications
    has_many :threads, :through => :publications

end

Below is my publications model:

class Publication < ActiveRecord::Base
  attr_accessible :thread_id, :user_id
  belongs_to :thread
  belongs_to :user
end

Below is my threads model:

class Thread < ActiveRecord::Base
  attr_accessible :description, :name, :tag_list, :thumbnail_image, :status, :thread_type, :subtitle, :summary

  has_one :publication
  has_one :user, :through => :publication

end

Below is my #index action, in my threads_controller.rb:

def index
  @user = current_user
  @threads = @user.threads.all
  @publications = @user.publications.all
end

Below is the code from my index view, where I'm listing all of the user's publications:

%table
  %tr
    %th Publication
    %th User
    %th Created at

  - @publication.each do |publication|
    %tr
      %td= publication.thread_id
      %td= publication.user_id
      %td= publication.created_at
4

1 回答 1

1

请使用关联关系表。

%table
  %tr
    %th Publication
    %th User
    %th Created at

  - @publication.each do |publication|
    %tr
      %td= publication.thread.name
      %td= publication.user.username
      %td= publication.created_at
于 2013-07-01T02:31:07.067 回答