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:
If you continue to leave
@card.user = current_user
in yournew
action you can set a hidden input fieldcard[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.Try moving
@card.user = current_user
right before your@card.save
line in thecreate
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?
I'd suggest this design is problematic, and I'd recommend changing your database design as follows:
cars.dealership_id
can either refer todealerships.id
ordealerships.remote_id
.
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
Convert Durations in Ruby - Hh:Mm:Ss.Sss to Milliseconds and Vice Versa
How to Show Longer Traces in Rails Testcases
How to Interact with a Caldav Server from Ruby
Get All Products of Category and Child Categories (Rails, Awesome_Nested_Set)
Issue Installing Gems on Windows 7 with Proxy
Rails Gem Prawn, Image and Anchor
Do Ruby Objects Have a Size Limit
Obtaining Number of Block Parameters
Ruby How to Generate a Tree Structure Form Array
Include Module in All Minitest Tests Like in Rspec
What Does Bundle Install -Without Production Do
How to Get Records Created at The Current Month
Download a Carrierwave Upload from S3
How to Specify Regexp Options Using Regexp.Union
Warning While Installing The Rails Plugin
Ruby on Rails: Pluralize for Other Languages
How to Tell a Ruby Method to Expect a Specific Parameter Type