【问题标题】:Why is my nested attributes form not working in rails?为什么我的嵌套属性表单在 Rails 中不起作用?
【发布时间】:2013-11-01 16:04:30
【问题描述】:

我有一个名为 profile 的模型,它有很多工作。我正在使用 cocoon gem 以允许用户制作个人资料,然后在单独的页面上制作他们想要的任意数量的工作。个人资料表格工作正常。然而,工作表似乎并没有真正创造就业机会。由于用户需要先填写个人资料表格,然后才能填写工作表格,所以当他们到达工作表格时,它将自动转到个人资料控制器中的更新操作,而不是创建。我很确定问题出在配置文件控制器中。这是配置文件控制器:

def new
    if current_user.profile
        redirect_to edit_profile_path(current_user.profile_name)
    else
        @profile = Profile.new
    end
end


def create
    @profile = current_user.build_profile(profile_params)
    @profile.save
    if current_user.profile.invalid?
        render :new, :status => :unprocessable_entity
    else
        redirect_to profile_path(current_user.profile_name)
    end
end

def edit
    @profile = current_user.profile
end


def update
    #if current_user.profile.jobs.any?
        @profile_save = current_user.profile.update_attributes(profile_params)

        if current_user.profile.invalid?
            @profile = current_user.profile
            render :edit, :status => :unprocessable_entity
        else
            redirect_to profile_path(current_user.profile_name)
        end
end

private
def profile_params
      params.fetch(:profile, {}).permit(:title, 
            :category, :description, :state, :zip_code, :rate,
            jobs_attributes: [:firm, :position, :category, :description,
            :begin, :end, :_destroy])
end

我使用 fetch 而不是 require,否则我会收到一条错误消息,提示找不到配置文件。这是表格:

<%= simple_form_for @profile do |f| %>
  <h3> Jobs </h3>
    <%= f.simple_fields_for :jobs do |job| %>
     <%= render 'job_fields', :f => job %>
       <% end %>
     <%= link_to_add_association 'add job', f, :jobs %>
  <%= f.submit %>
<% end %>

这里是 job_fields 部分:

.nested-fields
 <%= f.input :firm, label: "Firm" %> <br>
  <%= f.input :position, label: "Position" %> <br>
  <%= f.input :category, label: "Category"%><br>
  <%= f.input :begin, label: "Beginning", collection: 1960..2013 %><br>
  <%= f.input :end, label: "End", collection: 1960..2013 %>
  <%= f.input :description, label: "Description"%><br>

  <%= link_to_remove_association "remove task", f %>

问题也可能是我从 HAML 翻译成 ERB,我认为我做错了。

此外,所有个人资料实际上都属于某个用户,但我认为这不会产生影响。提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails haml erb nested-forms nested-attributes


    【解决方案1】:

    如果问题是您想为Jobs 调用create 方法,则需要修改表单以显式使用post 方法。比如:

    <%= simple_form_for @profile, :url => new_jobs_path, :method => :post do |f| %>
      <h3> Jobs </h3>
        <%= f.simple_fields_for :jobs do |job| %>
         <%= render 'job_fields', :f => job %>
           <% end %>
         <%= link_to_add_association 'add job', f, :jobs %>
      <%= f.submit %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多