您好,我在Customer_Status和Customer之间有1:M的关系。 Customer_Status适用于许多客户。我把关联放在相应的模型中。
以下是我的架构
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
在我的客户索引视图中,我尝试从客户状态表中显示属性customer_status_desc
,而不是在Customers表中找到customerstatus_id
。
在客户索引视图中,我有:
<% @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和rails 4
客户控制器
def index
@customers = Customer.order(sort_col + " " + sort_dir)
end
答案 0 :(得分:2)
您的专栏customerstatus_id
应命名为customer_status_id
,并确保belongs_to :customer_status
模型中有Customer
。
答案 1 :(得分:2)
Class
和Module
名称是CamelCase - CustomerStatus
永远不会像Customer_Statuses
这样的邪恶混合。
其他常数是全部大写。这是红宝石翻译关心的唯一惯例。
其他一切都是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
复合词有些特殊情况,因为如果它是复数,则rails会将第一个词视为命名空间。
user_hobbies -> UserHobby
users_hobbies -> Users::Hobbies
加入表格有点特别。
在has_and_belongs_to_many
中,两者都是复数:
hobbies_users
对于has_many through:
,与rails相同的规则实际上会加载模型:
hobby_users HobbyUser