2016-08-28 116 views
0

我有一個名爲project的模型,另一個名爲invite。Rails 4 - 設置關聯的外鍵值

的關聯是:

項目

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隱藏字段。

任何人都可以看到我要去哪裏錯了嗎?

回答

0

問題在於其中一個隱藏表單字段中的語句current_user.profile.project_id

(錯誤信息指向該代碼,但我不知道爲什麼你有評論在後該行)

這個錯誤清楚地說,一個profile沒有project_id,並且用戶可以有多個項目。如果你想訪問project_id,你可以做這樣的事情。

<%= f.hidden_field :project_id, value: @project.id %> 

@project是從通過get_project方法的控制器訪問。

+0

否 - 我認爲錯誤信息指向這一行,但沒有註釋:<%= f.hidden_​​field:project_id,:value => @ invite.project_id%> – Mel

+0

錯誤消息沒有提及配置文件。它正在討論與project_id有關的錯誤。 – Mel

+0

未定義的方法'project_id'爲#錯誤表明'profile'實例沒有'project_id'方法。 –