我有一个小应用程序可以让“员工”通过“交易”签入和签出“项目”。这些是正在发挥作用的模型。我很难显示当前已签出的项目 - 虽然我已经阅读了有关范围的信息,但我很难让关联、范围和视图正常工作。我正在拔头发——我是新来的,所以请温柔一点。
我不太担心这个应用程序的性能,而且我知道视图中的嵌套条件是一件很糟糕的事情,而且我知道我应该使用局部变量,但这实际上只是针对 MVP。
数据库/schema.rb
ActiveRecord::Schema.define(:version => 20130516162824) do
create_table "employees", :force => true do |t|
t.string "phone"
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "items", :force => true do |t|
t.string "description"
t.string "assettag"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "transactions", :force => true do |t|
t.boolean "status"
t.integer "item_id"
t.integer "employee_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "transactions", ["employee_id"], :name => "index_transactions_on_employee_id"
add_index "transactions", ["item_id"], :name => "index_transactions_on_item_id"
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
模型/employee.rb
class Employee < ActiveRecord::Base
attr_accessible :name, :phone
has_many :transactions
has_many :items, :through => :transactions
end
模型/item.rb
class Item < ActiveRecord::Base
attr_accessible :assettag, :description
has_many :transactions
has_many :employees, :through => :transactions
scope :checked_out, -> { last_transaction.checkout }
end
模型/事务.rb
class Transaction < ActiveRecord::Base
attr_accessible :employee_id, :item_id, :status
belongs_to :employee
belongs_to :item
delegate :phone, :name, to: :employee
delegate :description, :assettag, to: :item
scope :last_transaction, -> { order('created_at DESC').limit(1) }
scope :checkin, where(:status => true)
scope :checkout, where(:status => false)
end
应用程序/视图/员工/show.html.erb
<% if @employee.items.checked_out %>
<h3>Currently Checked-OUT Items</h3>
<table>
<tr>
<th>Item ID</th>
<th style="padding-left:30px">Asset Tag</th>
</tr>
<% @employee.transactions.items.checked_out.reverse.each do |transaction| %>
<tr>
<td style="padding-left:30px">
<%= transaction.description %>
</td>
<td style="padding-left:30px">
<%= transaction.assettag %>
</td>
</tr>
<% end %>
</table>
<% end %>