我正在努力使这个表格在这里显示基于网站类型的某些字段。在这种情况下,我希望它显示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
答案 0 :(得分:0)
好吧,你回来的是 ActiveRecord::Relation
的对象,而不是你的 model instance
,因此错误是因为没有方法叫< type
中的强> ActiveRecord::Relation
。
这应该有效
@project = Project.where(:id == project).first
或
你也可以这样做
<% if @project.first.type == 'Website' %>
执行 @project.first.type
是有效的,因为 @project.first
正在返回 {{1}找到的模型的第一个实例}
答案 1 :(得分: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