0

我有一个房东和一个房东公司的模型。我试图在创建新的landlord_company后,将landlord_id传递给landlord_company表。我在landlord_company窗体中有一个f.hidden_​​field,但它不起作用。不在另一个表中保存唯一的ID - Rails 4

地主模式:

has_many :landlord_companies 

landlord_company模型:

belongs_to :landlord 

landlord_company控制器:

def new 
    @landlord_company = LandlordCompany.new 
end 

def create 
    @landlord_company = LandlordCompany.new(landlord_company_params) 
    @landlord = Landlord.find(params[:landlord_id]) 

    respond_to do |format| 
     if @landlord_company.save 
     format.html { redirect_to @landlord_company, notice: 'Landlord company was successfully created.' } 
     format.json { render :show, status: :created, location: @landlord_company } 
     else 
     format.html { render :new } 
     format.json { render json: @landlord_company.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

landlord_company形式:

<div class="feedback-container"> 
    <%= form_for @landlord_company, url: {action: "create"}, html: {class: "new.html.erb"} do |f| %> 
     <% if @landlord_company.errors.any? %> 
     <div id="error_explanation"> 
      <h2><%= pluralize(@landlord_company.errors.count, "error") %> prohibited this landlord_company from being saved:</h2> 

      <ul> 
      <% @landlord_company.errors.full_messages.each do |message| %> 
       <li><%= message %></li> 
      <% end %> 
      </ul> 
      </div> 
     <% end %> 

     <div class="field"> 
      <%= f.label :llc_name, class: "general-text-label" %><br> 
      <%= f.text_field :llc_name, class: "general-text-field" %> 
     </div> 
     <div class="field"> 
      <%= f.hidden_field :landlord_id, :value => params[:landlord_id] %> 
     </div><br> 
     <div class="actions"> 
      <%= f.submit "Submit", class: "btn btn-black btn-4x" %> 
     </div> 
    <% end %> 
    </div> 

的routes.rb:

resources :landlords do 
    member do 
     resources :landlord_companies 
    end 
end 
+0

在您的创建操作中,添加以下行:puts params.inspect并向我们显示控制台的输出。这可能是因为楼主标识没有发送到新的操作,因此无 – bkunzi01

+0

@ bkunzi01这是puts.params输出。 { “UTF8”=> “✓”, “authenticity_token”=> “3F/ZM/SbXO/0dCsQkTtYPh4HaDwk1f3HAJ77NpLNMw2FHMt0fXt2QxEpnoTbmSSnmQUfwmuPsrAAKl/meieDEA ==”, “landlord_company”=> { “llc_name”=> “2”, “landlord_id”= >“”},“commit”=>“Submit”,“controller”=>“landlord_companies”,“action”=>“create”,“id”=>“21”} –

回答

0

经过近一天的工作,我找到了错误。我错误地嵌套了我的资源。我把它们当作...

resources :landlords do 
    member do 
     resources :landlord_companies 
    end 
end 

......并且正在搞乱一切!菜鸟的错误。

1

更改您创建行动如下:

def create 
    @landlord_company = Landlord.landlord_companies.new(landlord_company_params) 

然后确保到landlord_id添加到白名单PARAMS在“landlord_company_params”方法,它会自动地为你处理关联。

+0

我做了你说的,现在得到一个NoMethodError - undefined方法'landlord_companies'为#

+0

任何想法,为什么这不工作? –

+0

您的房东_id是空白值“”,而它必须是房东的主键。你的新动作需要将params [landlord_id]传递给它,以便它可以通过隐藏的表单字段输入该值。 – bkunzi01

相关问题