Foreign Key (Class_Id) Not Populating in Belongs_To Association

Foreign key (class_id) not populating in belongs_to association

Right now, it appears as you are setting the user on the new action, but not on the create action.

I see 2 options, the latter being the better:

  1. If you continue to leave @card.user = current_user in your new action you can set a hidden input field card[user_id] which can contain the current user's id. This is a totally bad idea because anyone can just throw whatever they want into that field.

  2. Try moving @card.user = current_user right before your @card.save line in the create action. This way the user can't mess around with it, and it will set it to your card object when it's actually about to be saved.

How to write belongs_to association when the foreign key can refer to either of two different columns?

cars.dealership_id can either refer to dealerships.id or dealerships.remote_id.

I'd suggest this design is problematic, and I'd recommend changing your database design as follows:

alter table cars
add constraint fk_cars_dealerships
foreign key (dealership_id)
references dealerships (id)
on update cascade
on delete restrict
;

With this change, the association becomes clear.

belongs_to :dealership

Any way around putting hidden field in forms for resources with belongs_to association

You're right - that would be horrible. No need for hidden fields. Something like the following.

In your TasksController:

def new
@list = List.find(params[:list_id])
@task = @list.tasks.build
end

def create
@list = List.find(params[:list_id])
@task = @list.tasks.new(params[:task])

# etc
end

In your Task#new view:

<% form_for [@list, @task] ... %>
...
<% end %>


Related Topics



Leave a reply



Submit