2014-06-05 154 views
0

我想使它在這裏這種形式將顯示基於網站的類型某些領域。在這種情況下,我希望它顯示project.type == Website時的表單。查看不識別模型屬性? Rails

不過,我不斷收到

undefined method `type' for #<Project::ActiveRecord_Relation:0x007ffe1cb543a8> 

我相信,我可以正常調用.TYPE,因爲它工作在控制檯中。

這裏是我的文件:

#views/assets/_new_asset.html.erb 
<%= simple_form_for @asset do |f| %> 
<% if @project.type == 'Website' %> 
    <%= f.input :name %> 
    <%= f.input :url %> 
    <%= f.button :submit %> 
<% end %> 
<% end %> 

這裏是我的資產/控制器

#controller/assets_controller.rb 
class AssetsController < ApplicationController 

    def new 
     @asset = Asset.new 
     project = Asset.where(:project_id) 
     @project = Project.where(:id == project) 
     end 


    def create 
     @asset = current_user.assets.build(asset_params) 

    if @asset.save 
     flash[:notice] = "Asset successfully added." 
     redirect_to(@project, :action => 'show') 
    else 
     render(:action => 'new') 
    end 
    end 

    private 

    def asset_params 
    params.require(:asset).permit(:id, :type,:url, :page_rank, :rev_company ,:social_pages) 
    end 



end 
+0

先給這樣'<%@如果project.first.type == '網站' %>' – Pavan

+0

我認爲你的@project是一個項目的集合,你需要循環它,然後尋找它的類型 – Mandeep

回答

0

那麼,你得到回ActiveRecord::Relation的對象,而不是你的model instance,因此錯誤,因爲沒有方法稱爲type in ActiveRecord::Relation

這應該工作

@project = Project.where(:id == project).first 

OR

你可以這樣做太

<% if @project.first.type == 'Website' %> 

@project.first.type作品,因爲@project.first將返回第一該模型的實例被發現由where

+0

我試過這個,但由於某種原因它不工作,而是給了我聲明的其他部分。你有任何其他想法,爲什麼這可能是? – HarryLucas

0
#views/assets/_new_asset.html.erb 
<%= simple_form_for @asset do |f| %> 
    <% if (@project.type == 'Website') %> 
    <%= f.input :name %> 
    <%= f.input :url %> 
    <%= f.button :submit %> 
    <% else %> 
    You Should not see this line. 
<% end %> 

在控制器

#controller/assets_controller.rb 
class AssetsController < ApplicationController 

    def new 
     @asset = Asset.new 
     # As if i have no idea from where youre getting :project_id 
     # in your code so i changed that. add that to asset_params 
     # if required. Thanks!!! 
     @project = Project.where(id: params[:project_id]).take 
    end 

    def create 
     @asset = current_user.assets.build(asset_params) 

     if @asset.save 
     flash[:notice] = "Asset successfully added." 
     redirect_to(@project, :action => 'show') 
     else 
     render(:action => 'new') 
     end 
    end 

    private 

    def asset_params 
    params.require(:asset).permit(:id, :type,:url, :page_rank, :rev_company ,:social_pages) 
    end 

end