繁体   English   中英

查看无法识别模型属性? 滑轨

[英]View not recognising model attributes? Rails

我正在努力使该表格在此显示基于网站类型的某些字段。 在这种情况下,我希望它在project.type == Website时显示表单。

但是我不断

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

好吧,您将返回ActiveRecord::Relation的对象,而不是model instance ,因此返回错误,因为ActiveRecord::Relation没有所谓的type方法。

这应该工作

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

要么

你也可以这样

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

进行@project.first.type之所以有效,是因为@project.first返回由where找到的模型的第一个实例。

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM