English 中文(简体)
铁路3.1协会和计票?
原标题:Rails 3.1 associations and counting?

I have two models in my Rails application, Users and Calls. The model associations are set as follows:

<>strong>user model

has_many  :calls

<>唱名表决>

belongs_to  :user

我正试图在申请中打上目前用户的电话数目。

Currently, I am using the following string:

 <%= Call.count %>

哪些是行之有效的,但显然需要all<>>m>打电话,而不仅仅是现有用户发出的呼吁。

因此,我放弃了以下内容:

<%= current_user.Call.calls.count %>

我对如何做到这一点感到困惑。 我需要能够从任何地方打上计票,以便我能够根据过去30天等开始计算。

最佳回答

You don t really want to be putting database calls within views, you really want to put that into a controller. You d be looking for something like User.find(current_user.id).calls.count as this will then use the association of which you ve set up, or if you want to disregard the model relation you could do Call.where(:user_id => current_user.id).count

因此,将下文(正确行动)列入相关控制人员,同样也列入这一看法。

主计长

@count = Call. where (:user_id => current_user.id).count/code>

观点

<%=@count %>

问题回答

这是:

current_user.calls.count

您可以与任何用户目标做同样的事情:

user = User.find(1)
user.calls.count

届时,你能够掌握更多条件,以完成基于日期的计算:

user.calls.where("calls.created_at > ?", 30.days.ago).count




相关问题
What do you have in your Model class?

What do you have in your model classes. Generally if i use any framework or any library (Zend Framework) , my classes only have variable which is table name . I know that in complicated applications ...

Rails Model With Aggregrate Data (not backed by a table)

Id like to create a model in rails that does not correlate to a table in the database. Instead the model should dynamically pull aggregrate data about other models. Example: I have a Restaurant ...

Trouble changing databases for my models in codeigniter

I m making a website with two different databases. Let s say one is DB1, and the other is DB2. I ve set up my database.php in the config folder, so they each have the correct host/password/username/...

EMAIL server FSP model

For my assignment I need to develop FSP model for email server and client. I manage to write simple model which describes one user, server and his mailbox, but I am having problems changing this ...

Rails Custom Model Functions

I m in a databases course and the instructor wants us to develop an e-commerce app. She said we can use any framework we like, and now that we re halfway through the semester she decided that Rails ...