0

私はタイムトラッカーを構築しています。この顧客からの開始時間、終了時間、顧客およびプロジェクトでタイムスタンプを作成することができます。プロジェクトや顧客にどれだけの時間を費やしたかを知ることができます。Railsと "has_one"の関係。プロジェクトを顧客に割り当てます(タイムスタンプ)

"has_many"のテーブル間の関係は完全に動作しますが、 "has_one"関係に問題があります。

マイテーブル:

timestamps    customers    projects 
----------    ------------   ----------- 
id:integer    id:integer   id:integer 
desc:string    customer_name:string project_name:string 
customer_id:interger project_id:integer 

マイモデル:

timestamp.rb

class Timestamp < ActiveRecord::Base 
    has_one :customer 
    has_one :project, through: :customer 
end 

customer.rb

class Customer < ActiveRecord::Base 
    belongs_to :timestamp 
    has_many :projects, dependent: :destroy 
end 

project.rb

class Project < ActiveRecord::Base 
    belongs_to :customer 
end 

私の目標:タイムスタンプからTimestamp.create({desc: "Something", customer_id: "1", project_id: "6"})

  • 取得プロジェクト:Timestamp.find(1).customer.project
  • マイ

    1. は、関連する顧客とのプロジェクトで1つのタイムスタンプを作成します。問題:

      timestamp_idをプロジェクトテーブルに含めるとこの作業を行うことができますが、この方法では、新しいタイムスタンプを作成するときに、Railsはすべてのプロジェクトを特定のtimestamp_idで複製します。しかし私はタイムスタンプに1つのproject_idを割り当てたい。

      FYI:私はMYSQLデータベースでrails 4.2.6を使用しています。

    +0

    あなたのtimestamp.rbで 'has_many:projects、through::customer'であってはなりませんか? 1人の顧客に多くのプロジェクトがあるためです。意図的にhas_oneを使用すると、リストから最初のプロジェクトのみがフェッチされます –

    +0

    あなたの権利があります。しかし、これは問題を解決しません。でもありがとう! –

    +0

    あなたのアプリで 'Timestamp'とは何ですか?その目的は何ですか?また、Active Recordタイムスタンプとはどのように違いますか?これはXYの問題のような臭いがあり、機能不全のソリューションを機能コードに変えてしまっているからです。おそらくもっと良い方法があります。 – Substantial

    答えて

    1

    タイムスタンプごとにプロジェクトを複製して顧客を複製したくないので、タイムスタンプに外部キーのみを設定する必要があります。それによって、あなたは、次の列を持つテーブルを持っているしたい:

    Timestamps 
        customer_id:integer:index 
        project_id:integer:index 
    
    Customers 
    
    Projects 
        customer_id:integer:index 
    

    あなたが書くと列を削除するためにマイグレーションを実行し、そしてそれは上記になりますように列を追加する必要があります。

    その後、関連付けを変更します。

    class Timestamp < ActiveRecord::Base 
        belongs_to :customer # change to belongs_to 
        has_many :projects, through: :customer # you might not need this anymore because of the line below 
        belongs_to :project # add this line 
    end 
    
    class Customer < ActiveRecord::Base 
        has_one :timestamp # change to has_one 
        has_many :projects, dependent: :destroy 
    end 
    
    class Project < ActiveRecord::Base 
        belongs_to :customer 
        has_one :timestamp # add this line 
    end 
    

    その後、あなたは今、次の

    Timestamp.find(1).customer 
    Timestamp.find(1).project 
    Timestamp.find(1).projects # these projects are customer.projects and are not directly associated to the line above, so I don't think you would need to call this 
    
    0

    さてさて、おかげでみんなを使用することができます! @ Jay-Ar Polisarioあなたの答えは完璧には機能しませんでしたが、私の "has_one/has_many"関係について考えさせてくれました。そのため、これを数時間後に再考しました。ありがとうございました。同様の問題への答えを見つけるためにGoogleからここに来た誰もが、については

    先行ボードや紙の上にテーブルと列を描画開始します。関係を視覚的にする!これは正しい関係を理解するのに役立ちました。

    関連する問題