如何从视图中访问has_many关系?

时间:2012-05-05 09:56:18

标签: ruby-on-rails ruby activerecord

我有一个表单,我正在创建一个新项目。

= form_for(@project, :html => { :class => 'addProjectForm' }) do |f|
  #actions
    = f.submit
  %p
    = f.label :name
    %br
    = f.text_field :name, :class => 'projectName'
  %p
    = f.label :ticket
    %br
    = f.text_field :ticket, :class => 'ticket'
 %p
    = f.label "Crew Member Name"
    = f.label "Crew Member Role"
    %br
    = f.text_field :crew_members.name
    = f.collection_select :crew, CrewMember.all, :role, :role
    = f.submit "Add More Crew Members", :id => 'add-crew-member'
  %p

一切正常如下:crew_members.name。我一直在undefined method "name" for :crew_member:Symbol。所有以前的标签都在更新Project表,但我无法让CrewMembers更新。这是模型。

class CrewMember < ActiveRecord::Base
  attr_accessible :name, :role
  belongs_to :project
end

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在调用此表单的操作中创建一个对象@crew_member,我想这将是新操作:
@member = @project.build_crew_member(如果您使用的是铁轨3)或
@member = @project.crew_member.build(如果&lt; rails 3)

然后在表单中,使用fields_for表单标记来捕获crew_member字段:
 <%= f.fields_for :crew_member do |m|%>
<%= m.text_field :name%>