Nested forms fail when using an ActiveResource model, Rails 4
Asked Answered
C

1

6

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.

Control answered 10/4, 2014 at 16:50 Comment(5)
Have you seen this thread: #2035200 Double check the app routes.Subdivision
can you list your User model?Blankbook
@maximus, I edited my post and added the user model. At BaraaAl-Bourghli, I don't think it's related.Control
@Control could you please go to rails console type User and show the output? I suspect that you might forgot to create firsname field when you were generating User model.Elapse
@LukasMac, this is an ActiveResource model. There is not real model, it goes over REST API.Control
H
8

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

Hawking answered 14/4, 2014 at 15:40 Comment(2)
Thank you for your answer. However, it throws a 500 server error from the remote API. Do you know what kind of response it is expecting or what kind of request it makes? Should I prepare the API in a way?Control
It's making a call to "https://***.com/api/v1.0/users/new.json and it's expecting a valid json response with the attributes of a new user (from which it will populate the form). ActiveResource expects the API to be RESTful, but if your API is throwing a 500 then maybe it isn't - you should investigate what caused the 500 error at the other end and read up on REST if you aren't sure about it (this answer is a good place to start.Hawking

© 2022 - 2024 — McMap. All rights reserved.