2016-02-27 113 views
-3

我對rails很新穎。我有一個一對多的協會。 Table1帶有幾個字段。一個字段是標題位置,另一個字段是ccode。表2如何只有2個字段,第一個字段也是位置,第二個字段也是ccode。這個表只是爲了保持我的位置。在Table1中,當我創建一個對象時,我分配了ccode,並且我想從Table2中獲取相應的位置給ccode。表2 has_many表1和表1屬於表2。此外,我想在<table>標記中顯示索引視圖中的位置。我認爲我的視圖代碼看起來就像我找到的例子,我也足夠了解html。我得到的問題是我的Table2對象返回nil。Ruby on rails一對多關聯

這是我的Table1模型的樣子。

class Table1 < ActiveRecord::Base 
    belongs_to :table_2 

    require 'csv' 

    def self.import(file) 
     CSV.foreach(file.path, headers: true, row_sep: :auto, col_sep: "\t") do |row| 
      Table1.create! row.to_hash 
     end 
    end 
end 

這是我的Table2模型的樣子。

class Table2 < ActiveRecord::Base 
    self.table_name = 'table_2' 
    self.primary_key = 'ccode' 
    has_many :table1 
end 

這裏是Table1Controller樣子

class FinancialsController < ApplicationController 

    def index 
     @financials = Financial.all 
    end 

    def create 
     @financial_loc_ccode = FinancialLocCcode.create(location_code: params[:location_cd], ccode: @financials.ccode) 
    end 
end 

我沒有表2控制器,一切都在表1控制器完成,我想這是因爲當我開始這個項目已經有一個表爲表2創建。

就像我之前說過的,我對Rails很陌生,仍然在學習模型和控制器之間的關係,以及如何操縱數據,並且已經在html中顯示它。

任何幫助將不勝感激。

+0

你的問題是什麼? – jvillian

+0

那麼你的具體問題是該協會沒有發生?你提到表2返回零。什麼時候?當你創建table1對象時,你傳遞給他們一行...你是否也傳遞給他們一個Table2 ID?如果不是,那麼與Table2對象的關聯永遠不會發生。 – toddmetheny

回答

0

我將集中討論Table2爲零。

這是零,因爲你沒有創建它。

進入您的終端輸入rails g controller table2 create

打開該文件和空create方法裏面,你會創建新的表2的對象。

您可以通過多種方式做到這一點,但是當您關聯時最重要的一點是您需要在創建關聯時定義關聯。

我給你舉個例子:

比方說,我有一個用戶模式

用戶模型

class User < ActiveRecord::Base 
has_many :posts 

end 

現在讓我們假設我有一個Post模型和我想要的用戶能夠創建很多帖子。

郵政型號

class Post < ActiveRecord::Base 
belongs_to :user 

end 

現在,這是我們將利用自己的表2控制器的重要組成部分

當我創建一個新的職位,它有belongs_to用戶,爲此我們將盡這

柱控制器

class PostsController < ApplicationController 

    def create 
    #store the object that has many posts as a variable 
    @user = current_user 

    #the important part, when you create a post you need to do this 
    @post = @user.posts.create(post_params) 
    end 

end 

這裏發生的事情是,Rails在@user的所有權下創建新帖子。這就是你如何通過關聯建立關係。

我希望這有助於清理一些關係,如果不是這裏有一些文件可能也有幫助。

http://guides.rubyonrails.org/association_basics.html