Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested forms fail when using an ActiveResource model, Rails 4

I have problem with creating a form for my ActiveResource models but I can't seem to find a solution. The problem is that the model does not know the fields, and throws an error when I try to create a text field:

undefined method `firstname' for #<User:0x00000002946ec8>

For this form:

<%= form_for(@user) do |f| %>
<div class="field">
   <%= f.label :firstname %><br>
   <%= f.text_field :firstname %>
 </div>

This is my from my controller:

def new
  @user = User.new
end

Thie is my user model:

class User < ActiveResource::Base
  self.site = "https://***.com/api/v1.0/"
end

I tried the following, but that does not work well with ActiveResource models, it is somehow not able to store retrieved data anymore. user.firstname is empty, when i remove the line it is not...

attr_accessor :firstname, :lastname

Then I found the gem Fortify (https://rubygems.org/gems/fortify) but the last update was in 2010 and installing it doesn't work...

I hope someone is familiar with this problem and can help me in the right direction.

like image 875
Chris Avatar asked Apr 10 '14 16:04

Chris


1 Answers

You should be using .build[1] in your controller instead of .new[2], like:

@user = User.build

The reason is that .new with no params just creates an empty object, whereas .build first queries the api for what params it should be using, specifically for this usecase (see this thread for more details)

Docs:

  1. http://api.rubyonrails.org/v3.2.13/classes/ActiveResource/Base.html#method-c-build

  2. http://api.rubyonrails.org/v3.2.13/classes/ActiveResource/Base.html#method-c-new

like image 193
omnikron Avatar answered Oct 23 '22 22:10

omnikron