2013-06-29 116 views
0

我有三種模式:「用戶」,「出版物」和「線程」。用戶和線程是對象,而發佈是一個連接(使用has_many:through)。Rails:空user_id has_many:通過

當用戶創建一個新線程時,線程及其聯接(發佈)都成功創建 - 這很好。唯一的問題是,user_id在兩個都是空的。

僅供參考,我正在使用設計。

下面是我的用戶模型:

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 

下面是我的出版物型號:

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

下面是我的線程模型:

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 

下面是我的形式用於創建新線程:

= form_for [@user, @thread] do |f| 
    - if @thread.errors.any? 
    #error_explanation 
     %h2= "#{pluralize(@thread.errors.count, "error")} prohibited this thread from being saved:" 
     %ul 
     - @thread.errors.full_messages.each do |msg| 
      %li= msg 

    .field 
    %span Title: 
    = f.text_field :name 

    .actions 
    = f.submit 'Submit'  

下面是我在線程控制器創建行動:

def create 
    @user = User.find(params[:user_id]) 
    @thread = @user.threads.new(params[:thread]) 
    @thread.build_publication 
end 

下面是出版物表:

class CreatePublications < ActiveRecord::Migration 
    def change 
    create_table :publications do |t| 
     t.integer :user_id 
     t.integer :thread_id 

     t.timestamps 
    end 
    end 
end 

所有對象都成功創建,我似乎無法得到USER_ID經歷。

回答

0

我相信有需要在你的線程控制器的create動作略有變化:

def create 
    @user = User.find(params[:user_id]) 
    @thread = @user.threads.create(params[:thread]) 
    @thread.build_publication 
end 

你會發現,行動的第二線現在使用的create代替newcreate命令將創建一個新線程並將其保存。