I have a user model with a type column (i believe this is called a polymorphic association). A user can be one of two types: employee or employer. An employer can post projects. So projects belongs_to employer and an employer has_many projects. I have the following code in my projects controller:

def new
    @project = Project.new
end

def create
    project = current_user.project.build(project_params)
    project.save
    redirect_to project_path(project_params(:id))
end

def show
    @project = Project.find(params(:id))
end

private

def project_params
  params.require(:project).permit(:title, :category, :location, :budget, :description)
end

The problem is that when I try to submit the new form in the browser, i am told:

undefined method `project' for #<Employer:0x007ffd85cf3250>

I have made forms in rails many times. The only thing I am doing differently is the polymorphic association so my guess is the problem has something to do with that? Anyone have any ideas? Thanks. I also have a feeling my show method might be incorrect if anyone has any comments on that.

有帮助吗?

解决方案

Use projects with s since you are use has_many. project method would only be available if you had said employer has_one project.

Note that projects would return an array of projects rather than project object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top