Rails 4 - 设置相关的外键值

时间:2016-08-28 23:21:30

标签: ruby-on-rails nested-forms hidden-field

我有一个名为project的模型,另一个名为invite。

协会是:

项目

has_many :invites

邀请

belongs_to :project

我希望允许创建项目的用户向其他用户发送邀请,以加入他们处理项目。

我有一个表单来创建邀请,如下所示:

<%= simple_form_for(@invite, :url => invites_path) do |f| %>
            <%= f.hidden_field :recipient_id, :value => get_recipient_id %>
            <%#= f.hidden_field :project_id, :value => current_user.profile.project_id %>
            <%= f.hidden_field :project_id, :value => @invite.project_id %>
            <%= f.label :email %>
            <%= f.email_field :email %>
            <!-- This field should use :date_picker- but it isnt working -->
            <%= f.input :expiry, :as => :date, :label => "When do you need a response to this invitation?"  %>
            <%#= f.input :expiry, :as => :date_picker, :label => "When do you need a response to this invitation?"  %>


            <%= f.submit 'Send', :class=>"formsubmit" %>
            <% end %>

在上面的表单中,我正在尝试设置project_id值。

在邀请控制器中,我有:

class InvitesController < ApplicationController
    before_action :get_project

    def index
        @invites = @project.invites
    end

    def new
      # @invite = Invite.new
      @invite = @project.invites.build
    end

    def create
      @invite = Invite.new(invite_params)
      @invite.sender_id = current_user.profile.id
      # @project = Project.find(params[:project_id])

      if @invite.save
           #send existing user email invitation to join project team
           InviteMailer.existing_user_invite(@invite).deliver_later 
           format.html { redirect_to @project }

           @invite.recipient.project.push(@invite.project)
        else
            @invite.recipient.project.push(@invite.project)
             InviteMailer.new_user_invite(@invite, new_user_registration_path(:invite_token => @invite.token)).deliver
        end

         # oh no, creating an new invitation failed

    end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_invite
      @invite = Invite.find(params[:id])
    end

    def get_project
      @project = Project.find(params[:project_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def invite_params
      params[:invite].permit(:email, :project_id, :recipient_id)
    end   
end 

我认为行动前的get_project会得到项目。相反,我收到的错误是:

undefined method `project_id' for #<Profile:0x007fa179509b60>
Did you mean?  project_ids
               project_ids=
               projects
               object_id

错误消息指向project_id表单中的隐藏字段。

谁能看到我哪里出错了?

1 个答案:

答案 0 :(得分:0)

问题在于其中一个隐藏的表单字段中的语句current_user.profile.project_id

(错误消息指向此代码,但我不知道您为何在帖子中注释该行)

错误清楚地表明profile没有project_id,用户可以拥有多个项目。如果您想访问project_id,可以执行以下操作。

<%= f.hidden_field :project_id, value: @project.id %>
可以通过@project方法从控制器访问

get_project