2013-06-29 2 views
0

"User", "Publications"및 "Threads"의 세 가지 모델이 있습니다. 사용자와 스레드는 객체이고 게시는 join입니다 (has_many : through 사용).레일즈 : null user_id with has_many : through

사용자가 새 스레드를 만들면 스레드와 해당 조인 (게시)이 모두 성공적으로 만들어집니다. 유일한 문제는 user_id가 둘 다 null이라는 것입니다.

참고로, 저는 devise를 사용하고 있습니다. 난 형태로 아래

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 

된다

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

내 스레드 모델 :

다음
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 

내 출판물 모델입니다 : 아래

내 사용자 모델입니다 새 스레드를 만들 때 사용 :

다음은
= 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'  

스레드 컨트롤러 내 생성 작업입니다 :

모든 개체가 성공적으로 생성되어
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를 얻을 수없는 것 : 아래

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

는 출판물 테이블입니다 지나가 다. 지금 create 대신 new의 사용

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

당신은 그 행동의 두 번째 줄을 알 수 있습니다 : 나는 믿고

답변

0

는 스레드 컨트롤러의 생성 작업에 약간의 변화가있을 필요가있다. create 명령은 새 스레드를 만들어 저장합니다.