0

我有一个应用程序,其中 auser可以有很多people,可以有很多projects,可以有很多invoices

在我的invoice控制器中,我有这个动作:

def create
  project = current_user.projects.find(params[:invoice][:project_id])    
  @invoice = project.invoices.build(params[:invoice])
  if @invoice.save
    flash[:success] = "Invoice created."
    redirect_to invoices_path
  else
    render :action => "new"
  end
end

问题是只要没有project_id.

我明白这一点并尝试了这样的事情......

@invoice = current_user.people.projects.invoices.build(params[:invoice])

...但我得到一个undefined method projects错误。

我只是想确保一个新的invoice将自动与正确的关联,user并且没有人可以篡改它。

有没有办法做到这一点?

4

2 回答 2

1

这是一种实现您想要的方法。我在控制台中对此进行了测试,所以它应该可以工作。我搞砸了人/人的多元化,但你应该明白要点。我为模型提供了虚拟属性以进行测试。

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :persons

class Person < ActiveRecord::Base
  attr_accessible :person_name, :user_id
  belongs_to :user
  has_many :projects
  has_many :people_invoices
  has_many :invoices, through: :people_invoices

class Project < ActiveRecord::Base
  attr_accessible :person_id, :project_name, :user_i
  belongs_to :person
  has_many :invoices

class PeopleInvoice < ActiveRecord::Base
  attr_accessible :invoice_id, :person_id
  belongs_to :person
  belongs_to :invoice

class Invoice < ActiveRecord::Base
  attr_accessible :invoice_amount, :person_id
  belongs_to :project
  has_many :people_invoice
  has_many :persons, through: :people_invoices

我为每个模型提供了一些虚拟属性,您可以在上面的 attr_accessible 字段中看到这些属性。

在我的控制台中,我尝试了:

@user = User.new(name: "User")
@person = @user.persons.create(person_name: "Employee")
@project = @person.projects.create(project_name: "foo")
@invoice = @project.invoices.create(invoice_amount: 25)
@person_invoice = @person.people_invoices.create(invoice_id:1)

以这种方式使用您的关联,然后您可以调用:

@user = User.find(4)
<User id: 4, name: "User", created_at: "2012-10-19 20:18:28", updated_at: "2012-10-19 20:18:28"> 
@user.persons
=> [#<Person id: 5, user_id: 4, person_name: "Employee", created_at: "2012-10-19 20:19:00", updated_at: "2012-10-19 20:19:00">]
@person.invoices
[#<Invoice id: 1, project_id: 2, invoice_amount: 25, created_at: "2012-10-19 19:33:10", updated_at: "2012-10-19 19:33:10">]

由于关联,您应该能够找到与项目和人员相对应的发票,并将它们追溯到特定用户。由于关系是 has_many,因此您将获得返回给您的数组(注意最后两个控制台输出中的括号)。然后,您必须在一个块中循环浏览它们以查看或访问特定值。

希望这可以帮助!

于 2012-10-19T20:39:19.117 回答
-1

你应该使用through

class User < ActiveRecord::Base
    has_many :projects
    has_many :invoices, through: projects
end

class Invoice < ActiveRecord::Base
    has_many :projects
    has_one :user, through: projects
end

class Project < ActiveRecord::Base
    belongs_to :user
    belongs_to :invoice
end
于 2012-10-19T19:24:31.163 回答