Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arbitrary (non model attribute) values to a rails action?

I have a unidirectional relationship model between users (users have many relationships) which holds the ids of two given users along with user a's nickname for user b. I want to use a form to allow users to pass in an e-mail address of another user and the nickname. If a user with that email exists, then create a relationship between the users. If no user matches, create a new 'phantom' user with that email and then build the relationship.

I'm relatively new to rails, and first naively tried using the basic:

= form_for @relationship do |f|
    = f.label :email
    = f.text_field :email
    = f.label :nickname, "Nickname"
    = f.text_field :nickname
    = f.submit "Submit", class: "btn btn-large btn-primary"

This fails because the relationship model does not contain an email attribute. I then tried the following, thinking it might work because it didn't directly reference the relationship model.

= form_tag :controller => "relationships", :action => "create" do
    = label :email        
    = text_field :email
    = label :nickname, "Nickname"
    = text_field :nickname
    = submit "Submit", class: "btn btn-large btn-primary"

But that throws an error "wrong number of arguments (1 for 2)"

I could add an email field to the relationship model, but it's not needed apart from when I'll use it to look up the desired user. My plan was to use the email and nickname values passed to the create action in the relationship controller to either create the relationship or create a new user and then the relationship depending on the case. So how can I pass arbitrary values to a controller action?

like image 526
Mischawaka Avatar asked Jul 14 '12 22:07

Mischawaka


1 Answers

Use the first form, and just make an attr_accessor in your model the email attribute.

That basically makes a temporary variable that you can derive from something like a form, but it won't save into the database.

class Relationship < ActiveRecord::Base # <- Assuming that's the name of your Relationship model

  attr_accessor :email
like image 88
Trip Avatar answered Jan 04 '23 02:01

Trip