2015-10-28 58 views
1

你好,我有一個1:M的Customer_Status和客戶之間的關係。 Customer_Status適用於許多客戶。我把這些關聯放在相應的模型中。Rails命名約定問題?

下面是我的架構

create_table "customer_statuses", force: :cascade do |t| 
t.string "customer_status_desc" 
t.datetime "created_at",   null: false 
t.datetime "updated_at",   null: false 
end 

create_table "customers", force: :cascade do |t| 
t.integer "customerstatus_id" 
t.integer "customertype_id" 
t.string "first_name" 
t.string "last_name" 
t.string "primaryemail" 
t.string "secondaryemail" 
t.string "billingcity" 
t.string "billingstreet" 
t.integer "billingzip" 
t.integer "primaryphone" 
t.integer "secondaryphone" 
t.datetime "created_at",  null: false 
t.datetime "updated_at",  null: false 
end 

在我的客戶索引視圖我試圖顯示從客戶狀態表,而不是在客戶表中找到的customerstatus_id屬性customer_status_desc

在客戶索引視圖我有:

<% @customers.each do |customer| %> 
    <tr> 
    <td><%= customer.customer_status.customer_status_desc %></td> 
    <td><%= customer.customertype_id %></td> 
    <td><%= customer.first_name %></td> 
    <td><%= customer.last_name %></td> 
    </tr> 
<% end %> 

對於我的生活,我不能讓customer_status_desc顯示。我得到了錯誤undefined method customer_status_desc for nil:NilClass我試過命名方式不同,如customer.customerstatus.customer_status_desc

經過一番研究後,看起來命名約定是失控的。有沒有辦法解決這個問題,而不需要改變所有的名字。我可以幫助鐵軌瞭解我正在嘗試呼叫的內容嗎?或者可能通過查詢強制它?

編輯: 我使用的Postgres和軌道4個

客戶控制器

def index 
@customers = Customer.order(sort_col + " " + sort_dir) 
end 

回答

2

你列customerstatus_id應該命名爲customer_status_id,並確保你有你的Customer模型belongs_to :customer_status

2

紅寶石公約

ClassModule名稱首字母大寫 - CustomerStatus從來就不是一個邪惡的混合像Customer_Statuses

其他常數都是大寫。這是Ruby解釋器關心的唯一約定。

其他一切都是snake_case。屬性,方法名稱,局部變量。 Snakecase絕對可以將單詞拼湊成C風格。

Do    don't 

primary_email primaryemail, primaryEmail 

再次,Ruby解釋器並不關心,但你的同行程序員呢。 Ruby生態系統實際上非常一致。不要那傢伙

Rails慣例

在軌外鍵默認是關係名+ _id

所以如果你的模型belongs_to :customer_status。該列應該被命名爲customer_status_id

對於如何將類名映射到模型,Active Record有一些非常具體的約定。

表應該是複數和模式單一:

animals -> Animal 

複合詞是鐵軌會把第一個字(S)爲命名空間,如果它是複數有些特殊情況。

user_hobbies -> UserHobby 
users_hobbies -> Users::Hobbies 

連接表有點特別。

has_and_belongs_to_many都是複數:

hobbies_users 

對於has_many through:相同的規則,根據實際軌正常的表加載模型:

hobby_users HobbyUser 
+0

https://github.com/bbatsov/ruby風格指南 – max

+0

非常徹底的答案!注意:Rails將模型名稱映射到表名,而不是相反。因此,如果您有一個名爲'users_hobbies'的表,那麼它實際上可以用於_either_名爲'UsersHobby'的模型或名爲'Users :: Hobby'的模型。 – Nathan

+0

正確,我不知道爲什麼我使用了錯誤的單數形式...... – max