基本上,用户在项目页面上点击添加新网站,就像这样设置
<%= link_to 'Add Asset', new_website_path(:project_id => "#{@project.id}" ), class: 'btn btn-md btn-danger' %>
然后他们用一些数据填写表格。但是我想要它,以便当他们提交该表单时,项目ID(从他们刚刚打开的项目页面)保存在网站的project_id变量下,但由于某种原因,这不起作用。
class WebsitesController < ApplicationController
def new
@project = Project.find(params[:project_id])
@website = Website.new(:type => 'Website', :project_id => @project)
end
def create
@website = current_user.assets.build(website_params)
if @website.save
flash[:notice] = "Asset successfully added."
redirect_to(:controller => 'projects', :action => 'show', :id => @website.project_id)
else
render(:action => 'new')
end
end
private
def website_params
params.require(:website).permit(:id, :type,:url, :page_rank, :rev_company ,:social_pages)
end
end
为什么这不起作用,有什么遗漏吗?当我在控制台中检查时,我添加的所有网站都有一个nil的project_id。
当我在浏览器中访问表单时,这是地址:
http://localhost:3000/websites/new?project_id=1
此外,我认为它正在获得正确的项目ID,因为在表单中我有一个查看该项目ID的条件,以查看它是否属于类型网站:
#views/websites/new.html.erb
<div class="col-md-5 col-md-offset-3">
<div class="panel panel-default newasset">
<div class="panel-heading">
<h3 class="panel-title ptd"><%= "New #{@project.type}" %></h3>
</div>
<div class='panel-body'>
<div class='form group'>
<%= simple_form_for(@website, html: {class: 'form-group' }) do |f| %>
<% if (@project.type == 'Website') %>
<div class="col-xs-4 col-xs-offset-3">
<%= f.input :title, label: 'Website Name' %>
<%= f.input :url %>
<%= f.input :rev_company, label: "Revenue Company" %>
<%= f.input :social_pages, label: "Number of Social Sites" %>
<%= f.input :page_rank %><br />
<div class="form-actions">
<%= f.button :submit, class: 'btn btn-primary' %>
</div>
<% else %>
You should not see this
<% end %>
<% end %>
</div>
</div>
</div>
</div>
答案 0 :(得分:3)
假设您正确传递:project_id
,那么您需要在project_id
方法中允许website_params
。
def website_params
params.require(:website).permit(:id, :project_id, :type,:url, :page_rank, :rev_company ,:social_pages)
## ^
## Permit project_id
end
目前,您尚未允许使用字段project_id
,这就是它未被保存的原因。
对于 Rails 4+(具有强参数),您需要显式指定要保存在数据库中的字段。
答案 1 :(得分:0)
@project是一个对象,数据库必须是一个整数。 你应该致电:
@project.id
无论如何,最好的解决办法是:
def new
@project = Project.find(params[:project_id]
@website = @project.websites.build(:type => 'Website')
end
如果您声明了:belongs,并且has_one / many
,则允许rails通过模型执行他的magick关联